Advertisement
Guest User

Untitled

a guest
Oct 1st, 2014
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.56 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "fmt"
  6.     "net"
  7.     "os"
  8.     "strconv"
  9. )
  10.  
  11. const (
  12.     CONN_HOST = ""
  13.     CONN_PORT = "80"
  14.     CONN_TYPE = "tcp"
  15. )
  16.  
  17. func main() {
  18.     // Listen for incoming connections.
  19.     l, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
  20.     if err != nil {
  21.         fmt.Println("Error listening:", err.Error())
  22.         os.Exit(1)
  23.     }
  24.     // Close the listener when the application closes.
  25.     defer l.Close()
  26.     fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
  27.     for {
  28.         // Listen for an incoming connection.
  29.         conn, err := l.Accept()
  30.         if err != nil {
  31.             fmt.Println("Error accepting: ", err.Error())
  32.             os.Exit(1)
  33.         }
  34.  
  35.         //logs an incoming message
  36.         fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
  37.  
  38.         // Handle connections in a new goroutine.
  39.         go handleRequest(conn)
  40.     }
  41. }
  42.  
  43. // Handles incoming requests.
  44. func handleRequest(conn net.Conn) {
  45.     // Make a buffer to hold incoming data.
  46.     buf := make([]byte, 1024)
  47.     // Read the incoming connection into the buffer.
  48.     reqLen, err := conn.Read(buf)
  49.     if err != nil {
  50.         fmt.Println("Error reading:", err.Error())
  51.     }
  52.     // Builds the message.
  53.     message := "Hi, I received your message! It was "
  54.     message += strconv.Itoa(reqLen)
  55.     message += " bytes long and that's what it said: \""
  56.     n := bytes.Index(buf, []byte{0})
  57.     message += string(buf[:n-1])
  58.     message += "\" ! Honestly I have no clue about what to do with your messages, so Bye Bye!\n"
  59.  
  60.     // Write the message in the connection channel.
  61.     conn.Write([]byte(message))
  62.     // Close the connection when you're done with it.
  63.     conn.Close()
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement