54 lines
864 B
Go
54 lines
864 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
)
|
|
|
|
func startServer() net.Conn {
|
|
return setupServer(PORT)
|
|
}
|
|
|
|
func setupServer(port string) net.Conn {
|
|
// Listen for incoming connections on port 8080
|
|
ln, err := net.Listen("tcp", ":"+port)
|
|
if err != nil {
|
|
log(err.Error())
|
|
return nil
|
|
}
|
|
|
|
// Accept incoming connections and handle them
|
|
for {
|
|
conn, err := ln.Accept()
|
|
if err != nil {
|
|
log(err.Error())
|
|
continue
|
|
}
|
|
|
|
// Handle the connection in a new goroutine
|
|
go handleConnection(conn)
|
|
return conn
|
|
}
|
|
|
|
}
|
|
|
|
func handleConnection(conn net.Conn) {
|
|
// Close the connection when we're done
|
|
defer closeConnection("Server", conn)
|
|
|
|
for {
|
|
// Read incoming data
|
|
buf := make([]byte, 1024)
|
|
|
|
_, err := conn.Read(buf)
|
|
if err != nil {
|
|
//read = false
|
|
log(err.Error())
|
|
return
|
|
}
|
|
|
|
// Print the incoming data
|
|
fmt.Printf("Received: %s \n", buf)
|
|
}
|
|
|
|
}
|