Fantastic go language (chat room development)

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


"Disclaimer: Copyright All, welcome reprint, do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "


This is a blog about the development of chat room, the original address of the article from here. This article is very representative of the function in the code part of the content, do not want to say anything, just to its implementation of some necessary explanations. As for the code, you can read it here as well as jump to that blog and read on.


Package Mainimport ("FMT" "OS" "NET")////////////////////////////////////////////////////////////error checking///////////// Func checkerror (Err Error,info string) (res bool) {if (err! = nil) {FMT. Println (info+ "" + Err. Error ()) return False}return True}////////////////////////////////////////////////////////////server end receive data thread//number of references:/ /data connection conn//communication channel Messages//////////////////////////////////////////////////////////func Handler (Conn net. Conn,messages Chan string) {fmt. PRINTLN ("Connection is connected from ...", Conn. Remoteaddr (). String ()) BUF: = make ([]byte,1024) for{lenght, err: = conn. Read (BUF) if (CheckError (Err, "Connection") ==false) {Conn. Close () break}if lenght > 0{buf[lenght]=0}//fmt. Println ("rec[", Conn. Remoteaddr (). String (), "] Say:", String (buf[0:lenght)) Recivestr: =string (Buf[0:lenght]) messages <-recivestr}}/////////////// server sends data thread//////connection dictionary conns//data channel messages///////////////////// ///////////////////Func Echohandler (Conns *map[string]net. Conn,messages Chan string) {for{msg:= <-messagesfmt. PRINTLN (msg) for Key,value: = Range *conns {fmt. PRINTLN ("Connection is connected from ...", key) _,err: =value. Write ([]byte (msg)) if (err! = nil) {FMT. Println (Err. Error ()) Delete (*conns,key)}}}}////////////////////////////////////////////////////////////start server//parameters/ports Port Func startserver (Port string) {service:= ":" +port// StrConv. Itoa (port); Tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", Service) CheckError (err, "resolvetcpaddr") L,err: = Net. LISTENTCP ("TCP", TCPADDR) checkerror (err, "listentcp") Conns:=make (map[string]net. CONN) Messages: = Make (chan string,10)//Start server broadcast thread go Echohandler (&conns,messages) for {fmt. Println ("Listening ...") Conn,err: = L.accept () checkerror (err, "Accept") fmt. Println ("Accepting ...") conns[conn. Remoteaddr (). String ()]=conn//start a new thread go Handler (conn,messages)}}//////////////////////////////////////////////////Client send thread//number//Send connection Conn//////////////////////////////////////////////////////////func chatsend (conn Net. Conn) {var input stringusername: = Conn. Localaddr (). String () for {fmt. SCANLN (&input) if input = = "/quit" {fmt. Println ("Byebye..") Conn. Close () OS. Exit (0);} Lens,err: =conn. Write ([]byte (username + "Say:::" + input)] FMT. PRINTLN (Lens) if (err! = nil) {FMT. Println (Err. Error ()) Conn. Close () break}}}////////////////////////////////////////////////////////////client start function//Parameters//Remote IP address and port tcpaddr/// Func startclient (tcpaddr string) {tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", tcpaddr) checkerror (err, "RESOLVETCPADDR") conn, err: = Net. DIALTCP ("TCP", Nil, tcpaddr) checkerror (err, "dialtcp")//Start client send thread go chatsend (conn)//Start client rotation buf: = Make ([]byte, 1024x768) For{lenght, err: = conn. Read (BUF) if (CheckError (Err, "Connection") ==false) {Conn. Close () fmt. Println ("Server is dead ... Byebye ") os. Exit (0)}fmt. Println (String (buf[0:lenght))}}////////////////////Main program////parameter description://Start server side: Chat Server [port]eg:chat server 9090//start client:ch At client [Server Ip addr]:[server Port] Eg:chat client 192.168.0.74:9090///////////////////////////////////////////// Func Main () {if Len (OS. Args)!=3 {fmt. Println ("Wrong pare") os. Exit (0)}if OS. args[1]== "Server" && len (OS. Args) ==3 {startserver (OS. ARGS[2])}if OS. args[1]== "Client" && len (OS. Args) ==3 {startclient (OS. ARGS[2])}}


The main points of knowledge are as follows:


(1) The code contains the contents of the server and the client, assuming that the server, the direct input./chat server 9090 is OK, the client is also very easy, input./chat client:9090;


(2) The assumption is that the client, in fact, contains two parts, part of the Chatsend function, accept the user's input, and part of connect to the server, accept the relevant information;


(3) The assumption is that the server is slightly more complex and has three components. The first part is the constant acceptance of each client; the second is to create a handler function for each client, accepting the message from the client; the third is the Echohandler function, Its role is to broadcast the information received from a user to all other clients, it is so simple.




< br>

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.