refactor to use bufReader.ReadBytes when accepting incoming messages from the connection socket

This commit is contained in:
Tim Williams 2018-07-27 14:03:15 -04:00
parent 4833f428e5
commit 8cc8da8ea5

View file

@ -3,7 +3,8 @@ package main
//@NOTE SHYFT main func for api, sets up router and spins up a server
//to run server 'go run shyftRingWalletConn/*.go'
import (
"bytes"
//"bytes"
"bufio"
"fmt"
"github.com/ShyftNetwork/go-empyrean/common/hexutil"
"github.com/ShyftNetwork/go-empyrean/crypto"
@ -16,6 +17,7 @@ const (
CONN_HOST = "localhost"
CONN_PORT = "3333"
CONN_TYPE = "tcp"
NEW_LINE_BYTE = 0x0a
)
var testAddrHex = "14791697260E4c9A71f18484C9f997B308e59325"
@ -50,19 +52,17 @@ func main() {
// Handles incoming requests.
func handleRequest(conn net.Conn) {
// Make a buffer to hold incoming data.
// Read the incoming connection into the buffer.
go func() {
buf := make([]byte, 1024)
msgBuf := make([]byte, 0)
var prevMsg []byte
var addressOfClient []byte
var signatureFromClient []byte
var msgFromClient []byte
bufReader := bufio.NewReader(conn)
for {
msg, err := conn.Read(buf)
msg, err := bufReader.ReadBytes(NEW_LINE_BYTE)
if err == io.EOF {
fmt.Println("END OF FILE, CLOSING CONNECTION")
conn.Close()
@ -74,28 +74,23 @@ func handleRequest(conn net.Conn) {
break
}
msgBuf = append(msgBuf, buf[:msg]...)
index := bytes.IndexByte(msgBuf, 0x0a)
for index != -1 {
newMsg := msgBuf[:index]
rest := msgBuf[(index + 1):len(msgBuf)]
msgBuf = rest
index = bytes.IndexByte(msgBuf, 0x0a)
msg = msg[:len(msg)-1] // remove trailing new line byte
// similar to shift in bash
if prevMsg != nil {
s := string(prevMsg[:])
if s == "-- ADDRESS --" {
addressOfClient = newMsg
addressOfClient = msg
}
if s == "-- SIGNATURE --" {
signatureFromClient = newMsg
signatureFromClient = msg
}
if s == "-- MESSAGE --" {
msgFromClient = newMsg
msgFromClient = msg
}
prevMsg = nil
} else {
prevMsg = newMsg
}
prevMsg = msg
}
if addressOfClient != nil && signatureFromClient != nil && msgFromClient != nil {
@ -122,7 +117,7 @@ func handleRequest(conn net.Conn) {
}
}
}()
go func() {
key, _ := crypto.HexToECDSA(testPrivHex)
f_msg := "Hello World"
@ -144,5 +139,5 @@ func handleRequest(conn net.Conn) {
conn.Write([]byte("\n"))
conn.Write(new_sig)
conn.Write([]byte("\n"))
}()
}