Socket server is a commonly used server in network services. It is easy to implement this business scenario using Go language.
Such network communication requires a server and at least one client.
We plan to build a communications project like this. After the server is started, wait for the client to access. The client sends a piece of information to the server. After the server receives the information, it will feedback it to the client.
First, we need to establish a server. The first thing the server needs to do is to "establish Socket port listening".
netListen, err := ("tcp", "localhost:1024")
In the above code, the table name listens to the native port 1024, and the communication protocol used is TCP.
When the listening is finished and the module task is completed, the netListen must be closed.
defer ()
Use the log function to enable the server window to see that the server is running.
Log("Waiting for clients ...")
Then use a for loop to wait endlessly for client information that you don't know when to access.
In the for loop body, you need to monitor the information reception of netListen:
conn, err := ()
When there is access from the client, access is accepted. And the client connection has been successfully connected to the logging process on the server side.
Log(().String(), "tcp connect success")
().String() represents the remote client.
Then, we start a goroutine to handle connection tasks.
go handleConnection(conn)
The processing process is to receive client information and feedback to client information.
n, err := (buffer)
([]byte(strTemp))
Server code example
package main import ( "net" "fmt" "os" "log" "time" ) func main() { //Create socket port monitoring netListen, err := ("tcp", "localhost:1024") CheckError(err) defer () Log("Waiting for clients ...") //Waiting for client access for{ conn, err := () // Listen to receive if err != nil{ continue //If an error occurs, continue to the next loop. } Log(().String(), "tcp connect success") //TCP connection is successful go handleConnection(conn) } } //Processing connectionfunc handleConnection(conn ) { buffer := make([]byte, 2048) //Create a slice for{ n, err := (buffer) //Read the content transmitted by the client if err != nil{ Log(().String(), "connection error: ", err) return //The coroutine is terminated after an error (disconnection) occurs in the remote client connection. } Log(().String(), "receive data string:\n", string(buffer[:n])) //Return information to the client strTemp := "CofoxServer got msg \""+string(buffer[:n])+"\" at "+().String() ([]byte(strTemp)) } } //Log processingfunc Log(v ...interface{}) { (v...) } //Error handlingfunc CheckError(err error) { if err != nil{ (, "Fatal error: %s", ()) } }
The business logic of the client is to send information to the server and then receive feedback from the server.
conn, err := ("tcp", nil, tcpAddr)
Dial to the server using TCP protocol. If no error occurs, it means dialing. So the connection is successful on the client logging
("connection success")
Then, in this already open connection, the task of sending and receiving information is carried out. ([]byte(words)) is the sending information; (buffer) is the receiving information. If an error occurs in reception, the error is recorded:
Log(().String(), "waiting server back msg error: ", err)
And interrupt the process.
If no error occurs, the information received by the bar is recorded in the log.
Log(().String(), "receive server back msg: ", string(buffer[:n]))
Client code example
package main import ( "net" "fmt" "log" "os" ) //Send informationfunc sender(conn ) { words := "Hello Server!" ([]byte(words)) ("send over") //Receive feedback from the server buffer := make([]byte, 2048) n, err := (buffer) if err != nil { Log(().String(), "waiting server back msg error: ", err) return } Log(().String(), "receive server back msg: ", string(buffer[:n])) } //logfunc Log(v ...interface{}) { (v...) } func main() { server := "127.0.0.1:1024" tcpAddr, err := ("tcp4", server) if err != nil { (, "Fatal error: %s", ()) (1) } conn, err := ("tcp", nil, tcpAddr) if err != nil { (, "Fatal error: %s", ()) (1) } ("connection success") sender(conn) }
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.