Skip to content

Instantly share code, notes, and snippets.

@minustore
Created January 20, 2017 14:12
Show Gist options
  • Save minustore/1930d925467ad3aca88311f2e33b5d5c to your computer and use it in GitHub Desktop.
Save minustore/1930d925467ad3aca88311f2e33b5d5c to your computer and use it in GitHub Desktop.
simple golagn echo server
package main
import (
"fmt"
"net"
"os"
"bytes"
)
const (
CONN_HOST = ""
CONN_PORT = "8020"
CONN_TYPE = "tcp"
)
func main() {
// Listen for incoming connections.
l, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
for {
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
//logs an incoming message
fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
// Handle connections in a new goroutine.
go handleRequest(conn)
}
}
// Handles incoming requests.
func handleRequest(conn net.Conn) {
// Make a buffer to hold incoming data.
defer conn.Close()
defer fmt.Println("conn closed")
for{
buf := make([]byte, 1024)
// Read the incoming connection into the buffer.
rn, err := conn.Read(buf)
fmt.Printf("read %d\n",rn)
if err != nil {
fmt.Println("Error reading:", err.Error())
//break;
return
}
// Builds the message.
message := ""
n := bytes.Index(buf, []byte{0})
message += string(buf[:n])
fmt.Printf("recv message: %s\n", message);
// Write the message in the connection channel.
wn, err := conn.Write([]byte(message));
if err != nil {
fmt.Println("write err\n");
fmt.Println(err)
continue
//return
}
fmt.Printf("wirte %d\n", wn)
// Close the connection when you're done with it.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment