Last active
September 3, 2015 11:57
-
-
Save alekseyl1992/d13f4fa1c50141c6ed22 to your computer and use it in GitHub Desktop.
Go TCP server
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 main | |
import ( | |
"fmt" | |
"net" | |
"os" | |
) | |
const ( | |
CONN_HOST = "localhost" | |
CONN_PORT = "8080" | |
CONN_TYPE = "tcp" | |
) | |
func main() { | |
// Listen for incoming connections. | |
l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+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) | |
} | |
// Handle connections in a new goroutine. | |
go handleRequest(conn) | |
} | |
} | |
// Handles incoming requests. | |
func handleRequest(conn net.Conn) { | |
// Make a buffer to hold incoming data. | |
buf := make([]byte, 1024) | |
// Read the incoming connection into the buffer. | |
_, err := conn.Read(buf) | |
if err != nil { | |
fmt.Println("Error reading:", err.Error()) | |
} | |
// output | |
//s := string(buf[:reqLen]) | |
//fmt.Println(s) | |
// Send a response back to person contacting us. | |
conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 0\r\n\r\n")) | |
// Close the connection when you're done with it. | |
conn.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment