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.
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.
...
// 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).
// 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))
}
}