This is a creation in Article, where the information may have evolved or changed.
The first time to run to the Internet company internship. I feel like I'm making a quick progress. The first Zhou Gang wrote an HTTP server for the public number of the ordering system ~ The second week to start directly on the side of the self-taught go language side to write the socket server ...
because found Golang this piece of information is very little, next I will in the blog to the entire server coding, as well as the pits are recorded down ~
In Golang, the network protocol has been encapsulated very well, want to write a socket server, we do not need to like other languages for socket, bind, listen, receive and so on a series of operations headache, As long as the use of Golang in the net package can be very convenient to complete the operation of the connection ~
Here, the most basic socket-based server notation is given:
Package Mainimport ("FMT" "Net" "Log" "OS") Func main () {//build socket, listen port Netlisten, err: = Net. Listen ("TCP", "localhost:1024") checkerror (Err) defer netlisten.close () Log ("Waiting for Clients") for {conn, err: = Netlisten.accept () if err! = Nil {continue}log (conn. Remoteaddr (). String (), "TCP Connect Success") Handleconnection (conn)}}//handles the connection func handleconnection (conn net. Conn) {buffer: = make ([]byte, 2048) for {n, err: = Conn. Read (buffer) if err! = Nil {LOG (conn. Remoteaddr (). String (), "Connection error:", err) Return}log (Conn. Remoteaddr (). String (), "Receive Data string:\n", String (Buffer[:n]))}}func log (v. ... interface{}) {log. Println (v ...)} Func checkerror (err error) {if err! = Nil {fmt. fprintf (OS. Stderr, "Fatal Error:%s", err. Error ()) OS. Exit (1)}}
Well, the 10 lines of code in the Go language have 5 lines of error, and you can see that the server wants to build and accept a socket, and the core process is
Netlisten, err: = Net. Listen ("TCP", "localhost:1024")
Conn, err: = Netlisten.accept ()
N, err: = conn. Read (buffer)
In these three steps, through listen, Accept and read, we successfully bound a port and was able to read the content from that port ~
After the server is written, next is the client side, I handwritten a helloworld to everyone:
Package Mainimport ("FMT" "NET" "OS") Func sender (conn net. Conn) {words: = "Hello world!" Conn. Write ([]byte (words)) fmt. PRINTLN ("Send Over")}func main () {server: = "127.0.0.1:1024" tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", server) if err! = Nil {fmt. fprintf (OS. Stderr, "Fatal Error:%s", err. Error ()) OS. Exit (1)}conn, err: = Net. DIALTCP ("TCP", nil, tcpaddr) if err! = Nil {fmt. fprintf (OS. Stderr, "Fatal Error:%s", err. Error ()) OS. Exit (1)}fmt. PRINTLN ("Connect Success") Sender (conn)}
As you can see, the key to the client here is
TCPADDR, err: = Net. RESOLVETCPADDR ("TCP4", server)
Conn, Err: = Net. DIALTCP ("TCP", Nil, tcpaddr)
These two steps are primarily responsible for parsing ports and connections ~
After writing the server and client, let's run a look: ~ ~
Running successfully, console appears with the server waiting for the connection prompt:
Then we run the client:
Successfully connected to the server, let's look at the results of the server:
Server side successfully received our Hello-world, as for the following line of red words, is the hint of disconnection ~
Here, one of the most basic server-client frames to use the socket is out ~
If you want the server to be able to respond to requests from different clients, we just need to do so in the main portal of the server-side code.
In Handleconnection (conn net. Conn) This code is preceded by a go that allows the server to concurrently process requests from different client
The concurrent processing of Golang can be referred to here Golang parallel computing
Next, I will write about how to design a communication protocol in the server and client to achieve some of their own special requirements ~
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.