[Go] Data transfer services in the tcp


go to achieve a tcp service, the first is to monitor port, receiving a request, this place will be blocked waiting
When a client connects over, will open a tcp connection grountine to deal with this client, so you can handle multiple simultaneous connections

In the connection, to be recycled to read the data transmission over the client, so that you can not stop the data processing request client
in the read data, the read-only I every time a byte is received so easy to see what data, so when reading data must cycle stitching data received, in this cycle, if the read size 0 or read the bytes \ n, I exit the loop.

Because \ n of ascii coded as 10, so this is a slice of my byte data received tmpByte [0] to 10 when it is cut off

Can be seen by running the following code to collect data about the client transmitting an English character, and passing specific data collected to a Chinese character, the reference table ascii

The client passes: a
server receives:
1 [97] a byte, ASCII encoded as 97, corresponding to A
1 [13] a byte, ASCII encoded as 13, a corresponding control character CR, the home key
1 [10] a byte, ASCII encoded as 10, a corresponding control character LF, linefeed

The client passes: Your
server receives:
1 [228] three bytes
1 [189]
1 [160]
1 [13] below and maybe the same meaning of the above
1 [10]

Encoding the ascii, English characters a next byte, encoding UTF8, three bytes of a Chinese character

Complete code:

main Package 

Import ( 
    " FMT " 
    " NET " 
) 

FUNC main () { 
    // listening port 
    listener, _: = net.Listen ( " TCP " , " 0.0.0.0:5921 " )
     // cycle blocking reception, concurrent processing while a number of connections 
    for { 
        Conn, _: = listener.Accept () 
        go handleConn (Conn) 
    } 
} 
FUNC handleConn (Conn net.Conn) { 
    // cycle to stop processing data 
    for { 
        tmpByte: = the make ([] byte , 1) 
        Var ResData [] byte 
        // loop to read data 
        for { 
            len, _: = conn.Read (tmpByte)
             FMT .Println (len, tmpByte)
             // read length 0, or to read off to line feed off 
            IF len == 0 || tmpByte [ 0 ] == 10 { 
                BREAK 
            } 
            // splicing read data 
            ResData = the append (ResData, tmpByte ...) 

        } 
        STR: = FMT .Sprintf ( " received:% s \ the n- " , String (ResData))
        conn.Write([]byte(str))
    }
}

 

Guess you like

Origin www.cnblogs.com/taoshihan/p/11879335.html