Let’s build our own protocol using tcp and net package in go, part 1
Tags: go, beginners, programming, tutorial
Published: 2023-09-17 15:05:39




Building your own protocol using the TCP package in Go involves defining a set of rules for communication between a client and a server.

These rules determine how data is structured, how messages are framed, and how the client and server interact.

---

We are going to build our own custom protocol.

But before that we must know how to implement a custom net connection in golang where we have a server and clients connect to the server.

The clients sends messages to the server and we simply print those messages.

If you prefer the video format with indepth explanation

> https://www.youtube.com/watch?v=t5u-iHBgEUY

## Explaining the code

```go
func main() {
 // Create a TCP listener on localhost:3000
 l, err := net.Listen("tcp", "localhost:3000")
 if err != nil {
  log.Fatalln("couldn't listen to network")
 }

```

`main` Function: This is the entry point of the program. It does the following.

It attempts to create a TCP listener on localhost at port 3000 using the `net.Listen` function.

If an error occurs during this process, it logs an error message and exits the program using `log.Fatalln` .

```go
 for {
  conn, err := l.Accept()
  if err != nil {
   log.Fatalln("err while accept", err)
  }
  go handle(conn)
 }
}
```

Accepting Connections: Inside an infinite for loop, the code does the following...

It waits for incoming client connections using `l.Accept()` . When a client connection is accepted, it returns a new connection object (conn) and any potential errors.


If an error occurs during the acceptance of a connection, it logs an error message and continues listening for connections.

When a connection is successfully accepted, it spawns a new goroutine by calling the handle function with the conn as an argument.

This allows the server to handle multiple client connections concurrently.

```go
func handle(conn net.Conn) {
 // We keep reading all the messages from the connection
 // until the connection is closed.
 fmt.Println("connected to: ", conn.RemoteAddr())
 for {
  var buffer [1024]byte // 1KB buffer to read data
  _, err := conn.Read(buffer[:])
  if err != nil {
   log.Printf("err while reading from conn: %v, exiting ...", err)
   return
  }
  fmt.Println("message read: ", string(buffer[:]))
 }
}
```

`handle` Function: This function is called for each client connection. It handles the communication with connected clients.

It prints a message indicating that a connection has been established, including the remote address of the client.

Inside a loop, it uses a 1KB buffer (buffer) to read data from the client connection using conn.Read().

If an error occurs while reading data from the client, it logs an error message and returns from the function, effectively closing the connection.

Otherwise, it prints the received message to the console.


## Claps Please!

If you found this article helpful I would appreciate some claps 👏👏👏👏, it motivates me to write more such useful articles in the future.

Follow for regular awesome content and insights.

## Subscribe to my Youtube channel

Subscribe to my youtube channel if you are on the lookout for more such awesome content in video format.

> https://www.youtube.com/@dsysd-dev

## Follow me on twitter 🐥

Join me on Twitter for a daily dose of knowledge, fascinating trivia, and valuable insights.

Let’s embark on a journey of continuous learning and discovery together! Follow me to stay inspired and informed. 🚀

> https://twitter.com/dsysd_dev

## Subscribe to my Newsletter

If you like my content, then consider subscribing to my free newsletter, to get exclusive, educational, technical, interesting and career related content directly delivered to your inbox

> https://dsysd.beehiiv.com/subscribe

## Important Links

Thanks for reading the post, be sure to follow the links below for even more awesome content in the future.

Twitter: https://twitter.com/dsysd_dev
Youtube: https://www.youtube.com/@dsysd-dev
Github: https://github.com/dsysd-dev
Medium: https://medium.com/@dsysd-dev
Email: dsysd.mail@gmail.com
Telegram 📚: https://t.me/dsysd_dev_channel
Linkedin: https://www.linkedin.com/in/dsysd-dev/
Newsletter: https://dsysd.beehiiv.com/subscribe
Gumroad: https://dsysd.gumroad.com/
Dev.to: https://dev.to/dsysd_dev/