A Simple Go TCP Server and TCP Client

Golang is a new-ish programming language that has really come into its own. It is a portable language which runs across many platforms; but allows advanced system and memory access unlike other web programming languages. There are a number of readily available packages which extend the functionality of Go without re-inventing the wheel, so you should use one of them if possible. But, if not, here is a simple TCP server and client example for Golang.

In the spirit of my Simple TCP Server and TCP Client for Java; I wanted to revisit the topic with my new favorite language: Go.

To compile and run the program, first install golang. Then, create these two files:

tcp-server.go:

package main

import "net"
import "fmt"
import "bufio"
import "strings" // only needed below for sample processing

func main() {

  fmt.Println("Launching server...")

  // listen on all interfaces
  ln, _ := net.Listen("tcp", ":8081")

  // accept connection on port
  conn, _ := ln.Accept()

  // run loop forever (or until ctrl-c)
  for {
    // will listen for message to process ending in newline (\n)
    message, _ := bufio.NewReader(conn).ReadString('\n')
    // output message received
    fmt.Print("Message Received:", string(message))
    // sample process for string received
    newmessage := strings.ToUpper(message)
    // send new string back to client
    conn.Write([]byte(newmessage + "\n"))
  }
}

And then tcp-client.go:

package main

import "net"
import "fmt"
import "bufio"
import "os"

func main() {

  // connect to this socket
  conn, _ := net.Dial("tcp", "127.0.0.1:8081")
  for { 
    // read in input from stdin
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Text to send: ")
    text, _ := reader.ReadString('\n')
    // send to socket
    fmt.Fprintf(conn, text + "\n")
    // listen for reply
    message, _ := bufio.NewReader(conn).ReadString('\n')
    fmt.Print("Message from server: "+message)
  }
}

Run the server first with go run tcp-server.go. Then run the client with go run tcp-client.go. You can then type a message into the client, and the server will capitalize it and send it back to the client.

This program is a very simple example and does not include error handling. For example, it will freak when you abandon your client. But you get the general idea for how to get started writing a simple Golang program that created a TCP server and client.