cleaner handling of socket open

Signed-off-by: Jeff Carr <jcarr@wit.com>
This commit is contained in:
Jeff Carr 2019-05-09 18:04:40 -07:00
parent 24ae9a3033
commit b932251092
1 changed files with 53 additions and 11 deletions

View File

@ -7,6 +7,10 @@ import "net"
import "fmt"
import "bufio"
import "github.com/svent/go-nbreader"
import "git.wit.com/jcarr/dnssecsocket"
// import "github.com/gookit/config"
// import "git.wit.com/wit/gui"
@ -31,15 +35,11 @@ const (
CONN_PROTO = "tcp"
)
func socketToWIT() {
func socketToWIT(myhostname string) {
remoteAddr := CONN_HOST + ":" + CONN_PORT
log.Println("remoteAddr:", remoteAddr)
// localAddr := "librem15.lab.wit.com" + ":" + CONN_PORT
localAddr := "[2604:bbc0:3:3:0:10:0:1003]" + ":" + CONN_PORT
log.Println("localAddr:", localAddr)
localTCPAddr, err := net.ResolveTCPAddr("tcp", localAddr)
localTCPAddr := dnssecsocket.ResolveIPv6hostname(myhostname)
remoteTCPAddr, err := net.ResolveTCPAddr("tcp", remoteAddr)
// connect to this socket
@ -51,22 +51,33 @@ func socketToWIT() {
log.Println("socket connect failed. Not sure what to do here. os.Exit() ?")
return
}
defer conn.Close()
log.Println("socket connected to", CONN_PROTO, CONN_HOST, CONN_PORT)
fmt.Fprintf(conn, myhostname + "\n")
connStdin, _ := conn.File()
go nonBlockingReader(connStdin, os.Stdout)
// read in input from stdin
reader := bufio.NewReader(os.Stdin)
fmt.Fprintf(conn,"librem15.lab.wit.com\n")
for {
fmt.Print("Text to send: ")
text, _ := reader.ReadString('\n')
// send to socket
fmt.Fprintf(conn, text + "\n")
a, err := connStdin.Write([]byte(string(text + "\n")))
if (err != nil) {
fmt.Println("SOCKET DIED with err=", err, a)
return
}
// TODO: check the socket has died and exit here
}
/*
// listen for reply
newStdin, _ := conn.File()
newreader := bufio.NewReader(newStdin)
for {
@ -78,6 +89,7 @@ func socketToWIT() {
}
}
}
*/
}
func retrySocket() {
@ -85,6 +97,36 @@ func retrySocket() {
log.Println("Sleep for 1 seconds, then try to establish connection to WIT")
time.Sleep(1 * 1000 * 1000 * 1000)
// for now, loop until I figure out what to actually do
socketToWIT()
socketToWIT("librem15.lab.wit.com")
}
}
// pass in two file handles (1 read, 1 write)
func nonBlockingReader(readFileHandle *os.File, writeFileHandle *os.File) {
// create a nonblocking GO reader
newreader := bufio.NewReader(readFileHandle)
nbr := nbreader.NewNBReader(newreader, 1024)
for {
defer readFileHandle.Close()
defer writeFileHandle.Close()
totalCount := 0
for {
oneByte := make([]byte, 1024)
count, err := nbr.Read(oneByte)
if (err != nil) {
log.Println("count, err =", count, err)
return
}
totalCount += count
if (count == 0) {
time.Sleep(20 * time.Millisecond) // only check the buffer 500 times a second
if (totalCount != 0) {
log.Println("totalCount = ", totalCount)
totalCount = 0
}
}
writeFileHandle.Write([]byte(string(oneByte)))
}
}
}