~/Create a Socket Protocol in Golang
Jul 15, 2019
To create a socket protocol in Golang, use the net
package. Here is a simple TCP server and client example.
Server Example:
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
|
package main
import (
"net"
"fmt"
"bufio"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
defer ln.Close()
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message Received:", string(message))
conn.Write([]byte("Hello Client\n"))
}
|
Client Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package main
import (
"net"
"fmt"
)
func main() {
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
fmt.Fprintf(conn, "Hello Server\n")
buf := make([]byte, 1024)
n, _ := conn.Read(buf)
fmt.Println("Server replied:", string(buf[:n]))
}
|
This uses basic TCP sockets and demonstrates sending and receiving strings over the connection. Modify the protocol logic for your use case. See the net package documentation for more options.