The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/46881213 reprint please must indicate the source!
1,socket Service
Using Golang to develop the socket service is still very simple.
The socket libraries are all encapsulated.
Reference Documentation:
Https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/08.1.md
2, simple example
PackageMainImport("FMT" "NET" "OS" "Time")funcMain () {tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4",": 8080") CheckError (ERR) listener, err: = Net. LISTENTCP ("TCP", tcpaddr) checkerror (ERR) for{//Cycle processingConn, err: = Listener. Accept ()ifErr! =Nil{Continue}GoHandleclient (conn)//Create a goroutinue processing}}funcHandleclient (Conn net. Conn) {deferConn. Close () Daytime: = time. Now (). String () Conn. Write ([]byte(daytime))//don ' t care about return value //We ' re finished with the This client}funcCheckError (err Error) {ifErr! =Nil{FMT. fprintf (OS. Stderr,"Fatal Error:%s"Err. Error ()) OS. Exit(1) }}
Through net. LISTENTCP ("TCP", TCPADDR) creates a service,
Then use the For loop, through listener. Accept () to create a goroutinue processing.
testing, using the Telnet test
127.0.0.18080127.0.0.1...‘^]‘.2015-07-1417:33:59.602610026 +0800 CSTConnection closed by foreign host.
3, add interactive processing
When the client input parameters, the server can handle.
Here are a few questions one is the client input with a carriage return \ r \ n to replace.
The equals sign is used in a string comparison, but the byte conversion string is not the same length and requires special handling.
PackageMainImport("NET" "OS" "FMT" "Time" "Strings")funcMain () {//println (OS. Args[0]) //println ("Hello world!")TCPADDR, err: = Net. RESOLVETCPADDR ("TCP4",": 8080") CheckError (Err,1) Listener, err: = Net. LISTENTCP ("TCP", tcpaddr) checkerror (err,2) for{conn, err: = Listener. Accept ()ifErr! =Nil{Continue}GoHandleclient (conn)} OS. Exit(0)}funcHandleclient (Conn net. Conn) {Conn. Setreaddeadline (time. Now (). Add(2* Time. Minute))//Set two-minute timeout. User_cmd: = Make([]byte, -)//SET command for user input deferConn. Close () for{Read_len, err: = conn. Read (User_cmd)ifErr! =Nil{FMT. PRINTLN (ERR) Break}ifRead_len = =0{ Break //connection already closed by client}//fmt. Println (String (user_cmd)) //fmt. Println (Len (String (user_cmd)))//length is 128, not the length of the time string. //################### #需要特殊处理字符串, find each character and accumulate it. ####################CMD_STR: ="" forI: =0; I <Len(User_cmd); i + + {//println (Cmd_str[i]) ifUser_cmd[i] = =0{ Break}Else{Cmd_str + =string(User_cmd[i])} }//Replace characterCMD_STR = strings. Replace (CMD_STR,"\ r \ n","",-1)ifCmd_str = ="Time"{time_now: = time. Now (). String () Conn. Write ([]byte(Time_now)) }Else ifCmd_str = ="Exit"{//Exit command. Conn. Close ()} User_cmd = Make([]byte, -)//Clear last Read content}}funcCheckError (err error, numint) {ifErr! =Nil{FMT. fprintf (OS. Stderr,"%d) Fail error:%s ", NUM, err. Error ()) OS. Exit(1) }}
Client Telnet Call: When input time returns, when input exit closes the connection.
127.0.0.18080127.0.0.1...‘^]‘.time2015-07-1417:44:06.743505631 +0800 CSTexitConnection closed by foreign host.
4, summary
The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/46881213 reprint please must indicate the source!
It is also very convenient to use the Golang development server.
The code is very concise, and with the goroutinue you can write efficient service-side code.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Golang (4): Write socket service, simple support command