Network applications use sockets. Sockets is the raw network layer (TCP/UDP). Data is often transmitted using protocols, but sockets let you define your own protocols.

This example uses golang to setup a socket server.

Related course:
Learn How To Code: Google’s Go (golang) Programming Language

Socket server golang

introduction

To use sockets, load the net module, with the line import "net".
Then the steps are sequentially to listen on a network port, to accept an incoming connections and then to process incoming data in a loop.

1
2
3
4
5
6
7
8
9
10
11
...
// listen on port 8000
ln, _ := net.Listen("tcp", ":8000")

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

// run loop forever (or until ctrl-c)
for {
// process data
}

socket server example

The example below opens a socket server on port 8000 of your local computer.
If you name the program server.go, you can start it with go run server.go.

You can connect to the server with telnet, telnet 127.0.0.1 8000 or from another
computer in your local network. Then send any message, the server will receive them.

(make sure your firewall isn’t blocking).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Very basic socket server
// https://golangr.com/

package main

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

func main() {
fmt.Println("Start server...")

// listen on port 8000
ln, _ := net.Listen("tcp", ":8000")

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

// run loop forever (or until ctrl-c)
for {
// get message, output
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message Received:", string(message))
}
}