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.

25 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.

  9. Wow, amazing weblog format! How lengthy have you been running a blog for?

    you made running a blog look easy. The full look of your
    website is magnificent, as well as the content!

    You can see similar: dobry sklep and here ecommerce

  10. It seems like you’re repeating a set of comments that you might have come across on various websites or social media platforms. These comments typically include praise for the content, requests for improvement, and expressions of gratitude. Is there anything specific you’d like to discuss or inquire about regarding these comments? Feel free to let me know how I can assist you further!

  11. Simply desire to say your article is as surprising The clearness in your post is simply excellent and i could assume you are an expert on this subject Fine with your permission let me to grab your feed to keep up to date with forthcoming post Thanks a million and please carry on the gratifying work

  12. This website has quickly become my go-to source for [topic]. The content is consistently top-notch, covering diverse angles with clarity and expertise. I’m constantly recommending it to colleagues and friends. Keep inspiring us!

Leave a Reply

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

You May Also Like

PHP Script for controlling APC PDU via SNMP

This one is neat – you can control those APC PDU Power…

Closing a Firefox Window with Javascript

I recently had a problem where I was opening a browser window…

A phpBB 3 iPhone Style Theme With Option to Disable

A forum that I am an adminstrator for has been clamoring for an iPhone theme (style) for a long time now. In the past, I hadn’t seen any usable iPhone template for phpBB3, until now. View this entire post to view my modifications to a theme switcher for mobile devices, so that the end user can disable a mobile theme for their login if they should choose to do so.

Bash Script to Interface with Rsync Command

I created this Bash script as a project for the system administration…