Golang (4): Write socket service, Simple Support Command, golangsocket

Source: Internet
Author: User

Golang (4): Write socket service, Simple Support Command, golangsocket

The original 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 library is encapsulated.
Reference:
Https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/08.1.md

2. Simple Example
Package mainimport ("fmt" "net" "OS" "time") func main () {tcpAddr, err: = net. resolveTCPAddr ("tcp4", ": 8080") checkError (err) listener, err: = net. listenTCP ("tcp", tcpAddr) checkError (err) for {// loop processing conn, err: = listener. accept () if err! = Nil {continue} go handleClient (conn) // create a goroutinue handler} func handleClient (conn net. conn) {defer conn. close () daytime: = time. now (). string () conn. write ([] byte (daytime) // don't care about return value // we're finished with this client} func checkError (err error) {if err! = Nil {fmt. Fprintf (OS. Stderr, "Fatal error: % s", err. Error () OS. Exit (1 )}}

Use net. ListenTCP ("tcp", tcpAddr) to create a service,
Then use the for loop to create a goroutinue through listener. Accept.

Test. Use telnet for testing.

$ telnet 127.0.0.1 8080Trying 127.0.0.1...Connected to localhost.Escape character is '^]'.2015-07-14 17:33:59.602610026 +0800 CSTConnection closed by foreign host.
3. Added interactive processing.

When the client inputs parameters, the server can process them.
One of the following problems is that the input by the client must be replaced by the carriage return \ r \ n.
You can use equal signs for a string, but the length of the byte conversion string is different and special processing is required.

Package mainimport ("net" "OS" "fmt" "time" "strings") func main () {// 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 () if err! = Nil {continue} go handleClient (conn)} OS. exit (0)} func handleClient (conn net. conn) {conn. setReadDeadline (time. now (). add (2 * time. (Minute) // set the two-Minute timeout. User_cmd: = make ([] byte, 128) // set the user input command defer conn. Close () for {read_len, err: = conn. Read (user_cmd) if err! = Nil {fmt. println (err) break} if read_len = 0 {break // connection already closed by client} // fmt. println (string (user_cmd) // fmt. println (len (string (user_cmd) // The length is 128, not the length of the time string. // #################### Special processing strings are required. Locate each character and accumulate the characters. ################### Response _str: = "" for I: = 0; I <len (user_cmd ); I ++ {// println (pai_str [I]) if user_cmd [I] = 0 {break} else {pai_str + = string (user_cmd [I])} // Replace the character pai_str = strings. replace (cmd_str, "\ r \ n", "",-1) if cmd_str = "time" {time_now: = time. now (). string () conn. write ([] byte (time_now)} else if exist _str = "exit" {// exit the command. Conn. Close ()} user_cmd = make ([] byte, 128) // clear last read content} func checkError (err error, num int) {if err! = Nil {fmt. Fprintf (OS. Stderr, "% d) Fail Error: % s", num, err. Error () OS. Exit (1 )}}

Client telnet call: when the return time is input and exit is input, the connection is closed.

$ telnet 127.0.0.1 8080Trying 127.0.0.1...Connected to localhost.Escape character is '^]'.time2015-07-14 17:44:06.743505631 +0800 CSTexitConnection closed by foreign host.
4. Summary

The original connection is: http://blog.csdn.net/freewebsys/article/details/46881213 reprint please must indicate the source!

It is very convenient to use golang to develop the server.
The code is very concise. With goroutinue, you can write efficient server code.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.