Golang TCP socket

Source: Internet
Author: User

Golang TCP socket programming is similar to HTTP and also a request response method. TCP requests (IP address, protocol, and port) are similar to HTTP requests, now we can simulate a request and a response. The request party is called the client. go

Package mainimport ("FMT" "IO/ioutil" "Net" "OS") func main () {tcpaddr, err: = net. resolvetcpaddr ("tcp4", "127.0.0.1: 7777") // obtain a TCP address, tcpaddrcheckerror (ERR) Conn, err: = net. dialtcp ("TCP", nil, tcpaddr) // create a TCP connection: tcpconncheckerror (ERR) _, err = Conn. write ([] Byte ("head/HTTP/1.0 \ r \ n") // send the HTTP Request Header checkerror (ERR) result, err: = ioutil. readall (conn) // obtain the returned data checkerror (ERR) FMT. println (string (Result ) OS. Exit (1)} func checkerror (ERR error) {If Err! = Nil {FMT. fprintf (OS. stderr, "Fatal error: % s", Err. Error () OS. Exit (1 )}}



The reply party is called server. Go.

Import ("FMT" "Net" "OS" "time") func main () {tcpaddr, err: = net. resolvetcpaddr ("tcp4", ": 7777") // obtain a tcpaddrcheckerror (ERR) listener, err: = net. listentcp ("TCP", tcpaddr) // listen to a port checkerror (ERR) for {Conn, err: = listener. accept () If Err! = Nil {continue} daytime: = time. now (). string () Conn. write ([] Byte (daytime) Conn. close () }} func checkerror (ERR error) {If Err! = Nil {FMT. fprintf (OS. stderr, "Fatal error: % s", Err. Error () OS. Exit (1 )}}



Golang TCP socket

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.