Golang Socket Example

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

I wrote a socket to write it with Golang. Very concise, the following directly read the code on the line. The notes are written in great detail. Do not understand the comments below

Server-side

Package Mainimport ("Bufio" "FMT" "IO" "NET") Func main () {///Use the TCP protocol to listen on native 8080 Port list, err: = Net. Listen ("TCP", "127.0.0.1:8080") if err! = Nil {fmt. PRINTLN ("Network Monitor failed!") Fmt. PRINTLN (ERR)}//Remember to close the defer list. Close () for {//wait for the link to be assigned to C, ERRC, err: = List If there is a link. Accept () if err! = Nil {fmt. PRINTLN ("Bad link")}//there may be multiple requests sent over so here in parallel way go Handle (c)}}func Handle (conn net. Conn) {defer Conn. Close ()//Create a buffered *reader and read the corresponding data, err: = Bufio. Newreader (conn). ReadString (' \ n ')///If the data reads err will become EOF  this is not an error. If err! = Nil && Err! = Io. EOF {fmt. Println (Err. Error ())}fmt. PRINTLN (data)}

Client

The package Mainimport ("FMT" "NET" "OS") Func main () {///via TCP protocol is linked to native 8080 Port con, err: = Net. Dial ("TCP", "127.0.0.1:8080")//if there is an error stating that the link failed if err! = Nil {fmt. PRINTLN ("Connection server-side failure") FMT. Println (Err. Error ()) OS. Exit (0)}//Remember to close defer con. Close ()//start sending Hellonum to server side, write_err: = con. Write ([]byte ("Hello"))//If the write has a problem output corresponding error message if Write_err! = nil {fmt. Println (Write_err. Error ())}//If there is no problem. Displays the corresponding write length of FMT. PRINTLN (NUM)}


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.