refactor into new connections that use channels

This commit is contained in:
Tim Williams 2018-07-27 15:33:56 -04:00
parent bd83244bba
commit cad6a4ae24

View file

@ -5,11 +5,13 @@ package main
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"github.com/ShyftNetwork/go-empyrean/common/hexutil" //"github.com/ShyftNetwork/go-empyrean/common/hexutil"
"github.com/ShyftNetwork/go-empyrean/crypto" "github.com/ShyftNetwork/go-empyrean/crypto"
"io" "io"
"net" "net"
"os" "os"
"github.com/ShyftNetwork/go-empyrean/common/hexutil"
) )
const ( const (
@ -52,7 +54,10 @@ func main() {
// Handles incoming requests. // Handles incoming requests.
func handleRequest(conn net.Conn) { func handleRequest(conn net.Conn) {
go readerConn(conn) messages := make(chan []byte)
go readerConn(conn, messages)
go handleMessages(messages)
key, _ := crypto.HexToECDSA(testPrivHex) key, _ := crypto.HexToECDSA(testPrivHex)
@ -78,28 +83,14 @@ func handleRequest(conn net.Conn) {
} }
func readerConn(conn net.Conn) { func handleMessages(channel chan []byte) {
var prevMsg []byte var prevMsg []byte
var addressOfClient []byte var addressOfClient []byte
var signatureFromClient []byte var signatureFromClient []byte
var msgFromClient []byte var msgFromClient []byte
bufReader := bufio.NewReader(conn)
for { for {
msg, err := bufReader.ReadBytes(NEW_LINE_BYTE) msg := <-channel
if err == io.EOF {
fmt.Println("END OF FILE, CLOSING CONNECTION")
conn.Close()
conn = nil
break
}
if err != nil {
fmt.Println("Connection error: ", err)
break
}
msg = msg[:len(msg)-1] // remove trailing new line byte
//similar to shift in bash //similar to shift in bash
if prevMsg != nil { if prevMsg != nil {
@ -142,3 +133,26 @@ func readerConn(conn net.Conn) {
} }
} }
} }
func readerConn(conn net.Conn, channel chan []byte) {
bufReader := bufio.NewReader(conn)
for {
msg, err := bufReader.ReadBytes(NEW_LINE_BYTE)
if err == io.EOF {
fmt.Println("END OF FILE, CLOSING CONNECTION")
conn.Close()
conn = nil
break
}
if err != nil {
fmt.Println("Connection error: ", err)
break
}
msg = msg[:len(msg)-1] // remove trailing new line byte
channel <- msg
}
}