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:


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", "")
  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.

3 replies
  1. Jake Lodwick
    Jake Lodwick says:

    This was just what I needed, thanks!

    btw, when I copy and pasted the code examples on my Mac, newlines weren’t preserved. Attached image shows what I got. Typing everything out wasn’t a bad experience, actually. But in case you don’t know…

  2. Dinesh Appavoo
    Dinesh Appavoo says:

    It is just the page template which doesn’t preserve newline. If you simply copy to collabedit and copy back, should be fine. I do this when get stuck in Mac copy paste issues.:)

Comments are closed.