Golang simple tcp server

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.

18 comments
  1. 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. 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.:)

  3. I loved you even more than you’ll say here. The picture is nice and your writing is stylish, but you read it quickly. I think you should give it another chance soon. I’ll likely do that again and again if you keep this walk safe.

  4. I loved you better than you would ever be able to express here. The picture is beautiful, and your wording is elegant; nonetheless, you read it in a short amount of time. I believe that you ought to give it another shot in the near future. If you make sure that this trek is safe, I will most likely try to do that again and again.

  5. I loved you better than you would ever be able to express here. The picture is beautiful, and your wording is elegant; nonetheless, you read it in a short amount of time. I believe that you ought to give it another shot in the near future. If you make sure that this trek is safe, I will most likely try to do that again and again.

  6. Over the last week I eagerly started following this fantastic website, they have remarkable content for their community. The site owner has a real talent for informing visitors. I’m excited and hope they maintain their splendid skills.

  7. Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do it Your writing style has been amazed me Thank you very nice article

  8. This website is astounding. The radiant substance uncovers the administrator’s excitement. I’m awestruck and envision more such extraordinary presents.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Last Modified Date or Time on WordPress Template Page

I couldn’t readily find an answer to this question via the google.…

Password Protected Folder Gives 404 Not Found in WordPress Installation Sub-folder.

Came across this little maddening issue again today after fixing it a…

Adding a Module Position in a Joomla 1.5 Template

Adding a module position in a Joomla 1.5 template is not as…

Accessing Microsoft ODBC data sources in Linux

Developing web apps cross platform can be a pain sometimes, as the…