gop2p/peers.go

103 lines
1.8 KiB
Go

package main
import (
"net"
"os"
"fmt"
"strings"
"encoding/gob"
"bytes"
)
type peer struct {
address net.TCPAddr
listener net.TCPListener
connection net.TCPConn
lpt []peer
}
func (p* peer) SetAddr(port string) {
service := ":" + port
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
Check(err)
p.address = *tcpAddr
}
func (p* peer) StartListening() {
listener, err := net.ListenTCP("tcp", &p.address)
Check(err)
p.listener = *listener
fmt.Printf("(%s) Waiting for peer connections...\n", os.Args[1])
for {
conn, err := p.listener.Accept()
if err != nil {
continue
}
handleConnection(conn)
}
}
func (p* peer) Connect(remote peer) {
peerconn, err := net.DialTCP("tcp4", nil, &remote.address)
Check(err)
fmt.Println("Found a remote peer")
p.connection = *peerconn
p.lpt = append(p.lpt, remote)
}
func (p peer) Version(remote peer) {
_, err := p.connection.Write([]byte("Hello from " + os.Args[1]))
Check(err)
var buf [512]byte
n, err := p.connection.Read(buf[0:])
Check(err)
result := string(buf[0:n])
fmt.Println(string(result))
}
func (p peer) Transact(remote peer, txn transaction) {
var b bytes.Buffer
e := gob.NewEncoder(&b)
err := e.Encode(txn)
Check(err)
fmt.Println("Encoded struct ", b)
}
func handleConnection(conn net.Conn) {
// close connection on exit
defer conn.Close()
var buf [512]byte
for {
// read up to 512 bytes
n, err := conn.Read(buf[0:])
if err != nil {
return
}
message := string(buf[0:n])
fmt.Println(message)
tokens := strings.Split(message, " ")
if tokens[0] != "" {
response := "Hi " + tokens[2] + ", from " + os.Args[1]
// write the n bytes read
_, err2 := conn.Write([]byte(response))
if err2 != nil {
return
}
}
}
}