Created
November 7, 2015 14:40
-
-
Save kthakore/d61af85ebdf7f14c7c30 to your computer and use it in GitHub Desktop.
Testing Go TCP Connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo | |
import ( | |
"fmt" | |
"log" | |
"net" | |
) | |
var connection net.Conn = nil | |
func close() { | |
if connection != nil { | |
connection.Close() | |
connection = nil | |
} | |
} | |
func connect(loc string) { | |
if connection != nil { | |
close() | |
} | |
log.Print("Client Started") | |
connection, err := net.Dial("tcp", loc) | |
if err != nil { | |
log.Print("Cannot connect to server") | |
} | |
} | |
func sendMessage(message string) { | |
log.Print("SENT FROM CLIENT") | |
fmt.Fprintf(connection, "[prefix]" + message+ "\n") | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo | |
import ( | |
"fmt" | |
"log" | |
"net" | |
"log" | |
"sync" | |
) | |
func server(recvMsg func(conn net.Conn), loc string) { | |
log.Print("Server") | |
server, err := net.Listen("tcp", loc) | |
if server == nil { | |
panic("couldn't start listening: " + err.Error()) | |
} | |
go func() { | |
log.Print("PING .. waiting for connections:") | |
c, err := server.Accept() | |
if err != nil { | |
log.Print("ERROR IS: ", err) | |
} | |
log.Print("Accepted Connection") | |
recvMsg(c) | |
}() | |
} | |
func TestClient() { | |
log.Print("Start") | |
h, _ := os.Hostname() | |
log.Print("HOSTNAME: ", h) | |
var wg sync.WaitGroup | |
wg.Add(1) | |
recvMsg := func(conn net.Conn) { | |
defer wg.Done() | |
log.Print("RECV") | |
buf := make([]byte, 1024) | |
// Read the incoming connection into the buffer. | |
reqLen, err := conn.Read(buf) | |
log.Print("ReqLen is: ", reqLen) | |
if err != nil { | |
log.Print("Error reading:", err.Error()) | |
} | |
// DO YOUR TEST HERE! | |
log.Print(buf) | |
// Send a response back to person contacting us. | |
conn.Write([]byte("Message received.")) | |
// Close the connection when you're done with it. | |
conn.Close() | |
} | |
//Can randomize too! | |
loc = "127.0.0.1:1234" | |
go server(recvMsg, loc) | |
go client(loc) | |
wg.Wait() | |
// Clean up | |
close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment