The go language implements directed chat, the simplest.

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

The code does not comment, because I take this as a note to do, if interested in the go language, add me QQ we learn the new language together.

Service side: Message_server.go

Package Mainimport ("Container/list" "Encoding/json" "FMT" JSON "Go-json"//go-simplejson "net" "Sync" "Time") type Client _message struct {sender intreceiver intmethod stringbody string}type all_message struct {List *list. Listlock sync. Mutex}type Message struct {time Int64sender intmes string}var ip_port string = ": 5555" var message_map map[int]all_mes Sage = Make (Map[int]all_message) func main () {Con, _: = Net. Listen ("TCP", Ip_port) defer con.close () for {Con, _: = Con.accept () fmt. Println (time. Now (). Local (), ":", con. REMOTEADDR ()) go Connection (con)}}func Connection (Con net. Conn) {defer con. Close () for {Buf: = make ([]byte, 2048) n, e: = con. Read (BUF) if E! = Nil {break}if N = = 0 {continue}mes, err: = Json.newjson (Buf[:n]) if err! = nil {con. Write ([]byte ("NOT_OK")) continue} else {con. Write ([]byte ("OK"))}c_message: = Convert_json (Mes) Switch {case C_message.method = = "Put":P ut_message (c_message) Case C _message.method = = "Get": Buf: = make ([]byte, 2048) List: = Get_message (C_message.receiver) if List = = Nil {con. Write ([]byte ("0")) Continue}num: = Len (list) con. Write ([]byte (FMT. Sprint (Num))) n, E: = con. Read (BUF) checkerror ("Get", E) if string (buf[:n]) = = "Get_len_ok" {for _, V: = Range list {n, e: = con. Write (v) n, E = con. Read (BUF) checkerror ("Get_for", E) if string (buf[:n]) = = "Get_ok" {continue} else {Break}}}}}}func put_message (c_message Client_message) {var String message = Message{time. Now (). Unix (), C_message.sender, C_message.body}if Message_map[c_message.receiver]. List = = Nil {Message_map[c_message.receiver] = all_message{list:list. New ()}}m: = Message_map[c_message.receiver]m.lock.lock () m.list.pushfront (String) m.lock.unlock ()}func Get_message ( Num int) [][]byte {var message_list [][]byteif Message_map[num]. List = = Nil {return Nil}l: = Message_map[num]l.lock.lock () x: = L.list.len () for I: = 0; i < x; i++ {Date, _: = json. Marshal (L.list.remove (L.list.back ())) Message_list = append (message_list, Date)}l.lock.unlock () return message_list} Func checkerror (POS string, e error) {if E ! = Nil {fmt. Println (POS, ":", E)}}func Convert_json (Mes *json.json) client_message {var m client_messagemethod, _: = Mes.get ("method "). String () sender, _: = Mes.get ("sender"). INT () receiver, _: = Mes.get ("receiver"). Int () body, _: = Mes.get ("Body"). String () m = Client_message{sender, receiver, method, Body}return m}
Client: Send_message.go

Client I was divided into two small parts, one is specifically automatically received, one is the use of the message, I would like to do the two colleagues, but not under the GUI input output I do not know how to solve, so there is a two-part.

Package Mainimport (//"Encoding/json" "FMT" JSON "Go-json" "Net" "StrConv" T "time") type client_message struct {sender Intreceiver intmethod stringbody string}type Message struct {time int64sender intmes string}var Sender int = 12 3456789var receiver int = 1597805565//qqfunc main () {con, err: = Net. Dial ("TCP", "127.0.0.1:5555") defer con. Close () if err! = Nil {fmt. PRINTLN (ERR)}/* This logoff part is used to send messages, compile the time to write off a for loop. for {var Str stringfmt. Scan (&AMP;STR) if x: = Send_message (con, Str); String (x) = = "OK" {fmt. PRINTLN ("message sent successfully")}}*/for {//This for loop is used to receive messages and cannot be compiled with the previous one. If e: = Get_message (con); E! = nil {break}t.sleep (3e9)}}func S End_message (Con net. Conn, Str string) []byte {mes: = []byte (FMT. Sprintf (' {' sender ':%d, ' receiver ':%d, ' method ': '%s ', ' body ': '%s '} ', sender, receiver, ' put ', Str)) if 0 < Len (MES) && len (MES) <= 2048 {Buf: = make ([]byte, 2048) con. Write (MES) n, _: = Con. Read (BUF) return Buf[:n]} else {fmt. PRINTLN ("cannot be empty or send text beyond the Limit") return nil}}func get_message (Con net. Conn)Error {var Buf []byte = make ([]byte, 2048) mes: = []byte (FMT. Sprintf (' {' sender ':%d, ' receiver ':%d, ' method ': '%s ', ' body ': '%s '} ', sender, receiver, ' get ', ' ') ') _, E: = con. Write (MES) if E! = nil {fmt. PRINTLN ("Message acquisition failed") return E}s: = String (Checkresponse (con)) if s = = "OK" {Num, _: = StrConv. Atoi (String (Checkresponse (con))) if Num > 0 {con. Write ([]byte ("GET_LEN_OK")) for I: = 0; i < Num; i++ {N, _: = Con. Read (Buf) Result, _: = json. Newjson (Buf[:n]) sender, _: = Result.get ("sender"). Int () time, _: = Result.get ("Time"). Int64 () body, _: = Result.get ("Mes"). String () fmt. Println ("sender:", sender) Fmt. PRINTLN ("Send Time:", T.unix (times, 0). Format ("2006-01-02 03:04:05 PM"), "content:", body) con. Write ([]byte ("GET_OK"))}}}return nil}func checkresponse (Con net. Conn) []byte {Buf: = make ([]byte, 1024x768) n, e: = con. Read (BUF) if E! = nil {fmt. Println (e)}return Buf[:n]}

Client:

Service side:


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.