add SendMeassage and Test

pull/69/head
Minh Doan 6 years ago
parent 92b3929a69
commit f17ec205db
  1. 20
      p2p/message_reader.go
  2. 53
      p2p/peer_test.go

@ -94,3 +94,23 @@ ILOOP:
} }
return contentBuf.Bytes(), nil return contentBuf.Bytes(), nil
} }
func CreateMessage(msgType byte, data []byte) []byte {
buffer := bytes.NewBuffer([]byte{})
buffer.WriteByte(msgType)
fourBytes := make([]byte, 4)
binary.BigEndian.PutUint32(fourBytes, uint32(len(data)))
buffer.Write(fourBytes)
buffer.Write(data)
return buffer.Bytes()
}
func SendMessageContent(conn net.Conn, data []byte) {
msgToSend := CreateMessage(byte(1), data)
w := bufio.NewWriter(conn)
w.Write(msgToSend)
w.Flush()
}

@ -0,0 +1,53 @@
package p2p
import (
"bufio"
"net"
"testing"
)
func setUpTestServer(times int, t *testing.T, conCreated chan bool) {
t.Parallel()
ln, _ := net.Listen("tcp", ":8081")
conCreated <- true
conn, _ := ln.Accept()
defer conn.Close()
var (
w = bufio.NewWriter(conn)
)
for times > 0 {
times--
data, err := ReadMessageContent(conn)
if err != nil {
t.Fatalf("error when ReadMessageContent %v", err)
}
data = CreateMessage(byte(1), data)
w.Write(data)
w.Flush()
}
}
func TestNewNewNode(t *testing.T) {
times := 100
conCreated := make(chan bool)
go setUpTestServer(times, t, conCreated)
<-conCreated
conn, _ := net.Dial("tcp", "127.0.0.1:8081")
for times > 0 {
times--
myMsg := "minhdoan"
SendMessageContent(conn, []byte(myMsg))
data, err := ReadMessageContent(conn)
if err != nil {
t.Error("got an error when trying to receive an expected message from server.")
}
if string(data) != myMsg {
t.Error("did not receive expected message")
}
}
conn.Close()
}
Loading…
Cancel
Save