gop2p/peers.go

103 lines
1.8 KiB
Go
Raw Permalink Normal View History

2019-05-17 03:57:41 +00:00
package main
2019-05-14 14:48:31 +00:00
import (
"net"
"os"
"fmt"
"strings"
2019-05-17 21:12:40 +00:00
"encoding/gob"
"bytes"
2019-05-14 14:48:31 +00:00
)
2019-05-17 03:57:41 +00:00
type peer struct {
2019-05-14 14:48:31 +00:00
address net.TCPAddr
listener net.TCPListener
connection net.TCPConn
2019-05-17 03:57:41 +00:00
lpt []peer
2019-05-14 14:48:31 +00:00
}
2019-05-17 03:57:41 +00:00
func (p* peer) SetAddr(port string) {
2019-05-14 14:48:31 +00:00
service := ":" + port
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
2019-05-17 03:57:41 +00:00
Check(err)
2019-05-14 14:48:31 +00:00
p.address = *tcpAddr
}
2019-05-17 03:57:41 +00:00
func (p* peer) StartListening() {
2019-05-14 14:48:31 +00:00
listener, err := net.ListenTCP("tcp", &p.address)
2019-05-17 03:57:41 +00:00
Check(err)
2019-05-14 14:48:31 +00:00
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)
}
}
2019-05-17 03:57:41 +00:00
func (p* peer) Connect(remote peer) {
2019-05-14 14:48:31 +00:00
peerconn, err := net.DialTCP("tcp4", nil, &remote.address)
2019-05-17 03:57:41 +00:00
Check(err)
2019-05-14 14:48:31 +00:00
fmt.Println("Found a remote peer")
p.connection = *peerconn
2019-05-17 03:57:41 +00:00
p.lpt = append(p.lpt, remote)
}
func (p peer) Version(remote peer) {
_, err := p.connection.Write([]byte("Hello from " + os.Args[1]))
Check(err)
2019-05-14 14:48:31 +00:00
var buf [512]byte
n, err := p.connection.Read(buf[0:])
2019-05-17 03:57:41 +00:00
Check(err)
2019-05-14 14:48:31 +00:00
result := string(buf[0:n])
fmt.Println(string(result))
}
2019-05-17 21:12:40 +00:00
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)
}
2019-05-14 14:48:31 +00:00
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
}
}
}
}