simple-tcp-ip-server example
Using the standard net
package to build a simple tcp server
to handle requests concurrently over ip (tcp/ip).
Table of Contents,
GitHub Webpage
REST vs TCP/IP
REST does not have state, whereas tcp has an open connection and you
can assume a lot about the server.
HOW IT WORKS
The net
package lets us listen for tcp connections and
handle those requests over that connection.
-
Set which IP and port you would like to listen on,
server, err := net.Listen("tcp", "127.0.0.1:1234")
-
Create a connection for each request (concurrently),
conn, err := server.Accept()
go handleRequest(conn)
-
Create your handler handleRequest()
,
rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
cmd, err := rw.ReadString('\n')
-
Create your handler functions like handleAdd()
,
handleAdd(rw)
This illustration may help,
RUN
go run simple-tcp-ip-server.go \
requests.go handlers.go
Press return to exit.
You can interact with the tcp server in many ways
USING NETCAT
In another terminal, use the nc command which runs Netcat,
a utility for sending raw data over a network connection.
netcat -q -1 localhost 1234
nc -q -1 localhost 1234
Now you can issue commands such as,
ADD
4
5
SUBTRACT
5
4
You can have as many connections as you like open.