Go Language Practice _ implement one (client) to one (server-side) Chat room

Source: Internet
Author: User

First, the purpose

Use the go language to implement a server-side chat room with the client.

Software: goland,go1.9

Code Warehouse Address

Second, the idea

1, first start the server side, using the Listen_socket function to listen to the IP address of the client connection;

2, start the client, and send data to the server side, send the end of the port block, waiting for server-side messages;

3, the server receives the message sent by the client;

4, the server sends the data to the client, after the sending is finished;

5, the client receives a message sent by the server side, the port is blocked after the send end, waiting for the client's message;

6, repeat step 2-5;

7, if the server side receives the "close" message sent by the client, the server side closes the connection with the client, and continues to wait for the next client connection;

8, the client closes, the chat ends.

Third, Go Code implementation

Sever End

//One-to-one chatroom SeverPackage Mainimport ("FMT"    "Net")//var connmap map[string]*net. TcpconnFunc Main () {listen_socket, err:= Net. Listen ("TCP","127.0.0.1:8000")//turn on the listener interface    ifErr! = Nil {//If there is an errorFmt. Println ("Sever Error")} defer listen_socket. Close ()//Delay server-side shutdownFmt. Println ("Sever is wating ....")     for{conn, err:= Listen_socket. Accept ()//listening to the port of the client        ifErr! =Nil {fmt. Println ("Conn fail ...")} FMT. Println ("Connect client successed")//Show server-side connectivity Success        varMsgstring  //declaring msg as a string variable         for {            //start receiving messages sent by clientsmsg =""  //string msg is initially emptyData: = Make ([]byte,255)//Create and declare a data variable, 255-bitMsg_read, ERR: = conn. Read (data)//receive messages sent by the client, bytes assigned to Msg_read,err as error            ifMsg_read = =0|| Err! = Nil {//If the message read is 0 bytes or there is an errorFmt. Println ("Err")} MSG_READ_STR:=string(data[0: Msg_read])//Converts a msg_read_str byte format into a string form            ifMsg_read_str = ="Close"{//if the received client message is closeConn. Write ([]byte("Close"))                 Break            }            //FMT. Println (String (Data[0:msg_read]))Fmt. Println ("client say:", MSG_READ_STR)//receiving information from the clientFMT. Printf ("say to client:")//prompt to the client to say the wordsFmt. Scan (&MSG)//Enter the server side to say to the client//Conn. Write ([]byte ("Hello client\n"))//msg_write: = []byte (msg)Conn. Write ([]byte(msg))//Send the message to the client//server-side port congestion is caused here} fmt. Println ("Client close\n") Conn. Close ()//Close Connection    }}

Client Side

//One-to-one chatroom ClientPackage Mainimport ("FMT"    "Net") Func Main () {conn, err:= Net. Dial ("TCP","127.0.0.1:8000")    ifErr! =Nil {fmt. Println ("Conn fail ...")} Defer conn. Close () fmt. Println ("Connect Sever successed")    varMsgstring  //declaring msg as a string variable     for{msg=""  //initialize MSG as null valueFmt. Printf ("say to sever:") fmt. Scan (&MSG)//Enter the message that the client will send to the server side//FMT. PRINTLN (msg)//msg_write: = []byte (msg)//Conn. Write (Msg_write)Conn. Write ([]byte(msg))//information into byte stream form and send to server side//This causes the client program port to clog//FMT. Println ([]byte (msg))//wait for the server to send information backData: = Make ([]byte,255) Msg_read, err:=Conn. Read (data)ifMsg_read = =0|| Err! =Nil {fmt. Println ("Err")} MSG_READ_STR:=string(data[0: Msg_read]) ifMsg_read_str = ="Close"{Conn. Write ([]byte("Close"))             Break} fmt. Println ("Sever say:", Msg_read_str)} Conn. Close ()}

Iv. Summary

    • Write, Read, conn, scan function can cause the program to jam;
    • In the network, the data is usually transmitted in bytes, so the format conversion is required: The byte is sent by the string, and when it is received, the byte is converted to a string.

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.