Magical 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, welcome reprint, please 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 code in the function part of the content, do not want to say anything, but to its implementation of some necessary explanation. About the code, you can either read it here, or 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-side receive data thread//parameter:// 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}}/////////////// The server sends the data thread////parameter//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//Parameter//Port 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)}}//////////////////////////////////////////////////////////// CustomerEnd send thread//parameter//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 startup function//parameter//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,1024) 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: chat client [Server Ip Addr]:[ser Ver 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 contents of the server and client are included in the code, and if it is a server, it can be entered directly./chat server 9090, the client is also very simple, input./chat client:9090 is good;


(2) If the client, in fact, includes two parts of the content, part of the Chatsend function, accept the user's input, and the other part is connect to the server, accept the relevant information;


(3) If it is server, a little more complex, there are three components. The first part is to constantly accept the client; the second is to create a handler function for each client, accept the information sent by the client, and the third is the Echohandler function, which is to broadcast the information received from one user to all other clients. It's that simple.





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.