Use of the NET packet TCP socket in the Go language

Source: Internet
Author: User

First, through the socket we mock request NetEase

Package Main;import ("NET" "Log" "Io/ioutil" "FMT") Func Chkerror (err error) {if err! = Nil {log. Fatal (err);}} Func Main () {///We mock request NetEase server//resolvetcpaddr used to get a tcpaddr//net parameter is "TCP4", "TCP6", "tcp"//addr means domain name or IP address plus port number tcpaddr, ERR: = Net. RESOLVETCPADDR ("TCP4", "www.163.com:80"); Chkerror (err);//dialtcp establishes a TCP connection//net parameter is "TCP4", "TCP6", "TCP"// LADDR represents a native address, typically set to NIL//RADDR for remote address tcpconn, ERR2: = Net. DIALTCP ("TCP", Nil, tcpaddr), Chkerror (ERR2),//write data to Tcpconn, ERR3: = Tcpconn. Write ([]byte ("get/http/1.1 \r\n\r\n")); Chkerror (ERR3);//Read all data in Tcpconn, ERR4: = Ioutil. ReadAll (Tcpconn); Chkerror (ERR4);//print out data fmt. Println (String (data));}

 

Second, create a simple server through the socket

Package Main;import ("NET" "Log") Func Chkerror (err error) {if err! = Nil {log. Fatal (err);}} Func Main () {//Creates a TCP server-side tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", "127.0.0.1:8080"); Chkerror (err);//Listener Port Tcplisten, ERR2: = Net. LISTENTCP ("TCP", tcpaddr); Chkerror (ERR2);//The processing of a dead loop client requests for {//waits for a client's connection//Note here is conn that cannot concurrently handle multiple requests, ERR3: = Tcplisten. Accept ();//If there is an error directly skip if ERR3! = nil {continue;} Send data to the client and close the connection conn. Write ([]byte ("hello,client \ r \ n")]; Conn. Close ();}}

Test by Xshell's Telnet method.

Third, improve the above code, using Goroutine to process the user's request

Package Main;import ("Log" "NET" "Time") Func Chkerror (err error) {if err! = Nil {log. Fatal (err);}} Handle client requests separately Func CLIENTHANDLE (conn net). Conn) {defer Conn. Close (); Conn. Write ([]byte ("Hello" + time. Now (). String ()));} Func Main () {//Creates a TCP server-side tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", "127.0.0.1:8080"); Chkerror (err);//Listener Port Tcplisten, ERR2: = Net. LISTENTCP ("TCP", tcpaddr); Chkerror (ERR2);//The Processing of the dead loop client requests for {//waits for the client's connection conn, err3: = Tcplisten. Accept ();//If there is an error directly skip if ERR3! = nil {continue;} Handle user requests via Goroutine go Clienthandle (conn);}}

Four, continuous processing of requests sent by the client, according to the cmd command, different data returned.

Package Main;import ("NET" "Time" "Log" "strings") Func Chkerror (err error) {if err! = Nil {log. Fatal (err);}} Handle client requests separately Func CLIENTHANDLE (conn net). Conn) {//set to automatically turn off Connconn when the client has no data request within 3 minutes. Setreaddeadline (time. Now (). ADD (time. Minute * 3));D Efer Conn. Close ();//cyclic processing of the client's request for {data: = make ([]byte, 256);//read data from Conn N, err: = conn. Read (data)//If the read data size is 0 or an error exits if n = = 0 | | Err! = nil {break;} Remove both whitespace character cmd: = strings. Trimspace (String (data[0:n]));//data sent to the client Rep: = ""; if (cmd = = "string") {rep = "hello,client \ r \ n";} else if (cmd = = "Time") {rep = time. Now (). Format ("2006-01-02 15:04:05"); Send Data Conn. Write ([]byte (Rep));}} Func Main () {tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", "127.0.0.1:8080"); Chkerror (err); Tcplisten, ERR2: = Net. LISTENTCP ("TCP", tcpaddr); Chkerror (ERR2); for {conn, err3: = Tcplisten. Accept (); if err3! = nil {continue;} Go Clienthandle (conn);}}

Use of the NET packet TCP socket in the Go language

Related Article

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.