khml1g
Last Updated: February 25, 2016
·
2.784K
· L1fescape

Simple TCP Server in Go

Listens on port 8081 for a tcp connection. Once a connection has been made, the request data is read, printed to the console, and the string "Hello!" is returned as a response.

package main

import (
  "net"
  "fmt"
)

func handleConnection(conn net.Conn) {
  // try to read data from the connection
  data := make([]byte, 512)
  n, err := conn.Read(data)
  if err != nil { panic(err)  }
  s := string(data[:n])

  // print the request data
  fmt.Println(s)

  // send a response
  var str = []string{"Hi there!"}
  var x = []byte{}
  // convert string array to byte array so it can
  // be written to the connection
  for i:=0; i<len(str); i++{
    b := []byte(str[i])
    for j:=0; j<len(b); j++{
      x = append(x,b[j])
    }
  }
  // write the data to the connection
  _, err = conn.Write(x)
  if err != nil { panic(err) }
  // close the connection
  conn.Close()
}

func main() {
  ln, err := net.Listen("tcp", ":8081")
  if err != nil {
    // handle error
  }
  for {
    conn, err := ln.Accept()
    if err != nil {
      // handle error
      continue
    }
    go handleConnection(conn)
  }
}

3 Responses
Add your response

12629

Instead of the double loop to convert the string array to a byte array, why not do:

// import "bytes"
var str = []string{"Hi there!"}
var buf bytes.Buffer
for _, s := range str {
    buf.WriteString(s)
}
_, err = conn.Write(buf.Bytes())

To simplify things further, you could import the "strings" library and call strings.Join() on the str array.

If net.Conn complies with the io.Reader interface, you could also use bytes.Buffer for reading from the connection. I don't think it does comply, however.

over 1 year ago ·
12631

Thanks for the tips! I updated the code and put it in a gist here: https://gist.github.com/L1fescape/8888393

Just started learning Go last week, so all tips/suggestions are welcome!

over 1 year ago ·
12675

I am starting learning dart too :) Thx. Ooops Dart with go! :D

over 1 year ago ·