Skip to content

Commit

Permalink
examples: example using swarm and raw tcp (no muxing)
Browse files Browse the repository at this point in the history
  • Loading branch information
whyrusleeping committed Sep 3, 2016
1 parent c3e3162 commit 350f87d
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
16 changes: 16 additions & 0 deletions examples/justtcp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# libp2p 'just tcp' example

## What this does
This example starts up a libp2p swarm that listens for tcp connections behind a
multistream muxer protocol of `/plaintext/1.0.0`. All connections made to it
will be echoed back.

## Building
```
$ go build
```

## Usage
```
$ ./justtcp
```
85 changes: 85 additions & 0 deletions examples/justtcp/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package main

import (
"context"
"fmt"
"net"
"os"

transport "github.com/ipfs/go-libp2p-transport"
ma "github.com/jbenet/go-multiaddr"
smux "github.com/jbenet/go-stream-muxer"
"github.com/libp2p/go-libp2p/p2p/net/swarm"
)

func fatal(i interface{}) {
fmt.Println(i)
os.Exit(1)
}

type NullMux struct{}

type NullMuxConn struct {
net.Conn
}

func (c *NullMuxConn) AcceptStream() (smux.Stream, error) {
panic("We don't do this")
}

func (c *NullMuxConn) IsClosed() bool {
return false
}

func (c *NullMuxConn) OpenStream() (smux.Stream, error) {
panic("if only you could see how disappointed i am in you right now")
}

func (c *NullMuxConn) Serve(_ smux.StreamHandler) {
}

func (nm NullMux) NewConn(c net.Conn, server bool) (smux.Conn, error) {
return &NullMuxConn{c}, nil
}

var _ smux.Transport = (*NullMux)(nil)

func main() {
laddr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/5555")
if err != nil {
fatal(err)
}

swarm.PSTransport = new(NullMux)

s := swarm.NewBlankSwarm(context.Background(), "bob", nil)

s.AddTransport(transport.NewTCPTransport())

err = s.AddListenAddr(laddr)
if err != nil {
fatal(err)
}

s.SetConnHandler(func(c *swarm.Conn) {
fmt.Println("CALLED OUR CONN HANDLER!")
defer c.Close()
buf := make([]byte, 1024)
for {
n, err := c.RawConn().Read(buf)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("read: %q\n", string(buf[:n]))

_, err = c.RawConn().Write(buf[:n])
if err != nil {
fmt.Println(err)
return
}
}
})

<-make(chan bool)
}

0 comments on commit 350f87d

Please sign in to comment.