Private Chat Service for Golang

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

A simple Golang implementation of private chat, determined by server-side 22 matches
Server-Side Chat_server.go

Package Mainimport ("FMT" "io" "Log" "NET") const LISTENADDR = "localhost:4000" Func Main () {L, err: = Net. Listen ("TCP", LISTENADDR) if err! = Nil {log. Fatal (Err)} for {c, err: = L.accept () if err! = Nil {log. Fatal (ERR)}//go io. Copy (c, c) go Match (c)}}var partner = make (chan io. Readwritecloser) func match (c io. Readwritecloser) {fmt.    Fprint (c, "Waiting for a partner ...") Select {case partner <-C://Now handled by the other Goroutine Case P: = <-partner:chat (P, c)}}/*func chat (A, b io. Readwritecloser) {fmt. Fprintln (A, "Found one!    Say hi. ") Fmt. Fprintln (b, "Found one!    Say hi. ") Go IO. Copy (A, b) Io. Copy (b, a)}*/func chat (A, b io. Readwritecloser) {fmt. Fprintln (A, "Found one!    Say hi. ") Fmt. Fprintln (b, "Found one!    Say hi. ") ERRC: = Make (chan error, 1) go CP (A, B, ERRC) go CP (b, A, ERRC) if err: = <-errc; Err! = Nil {log. PRINTLN (ERR)} A.cloSE () b.close ()}func CP (W IO). Writer, R io. Reader, ERRC chan<-error) {_, Err: = Io. Copy (W, R) ERRC <-Err}

Client Chat_client.go:

package mainimport (    "fmt"    "log"    "net")func main() {    l, err := net.Dial("tcp", "localhost:4000")    if err != nil {        log.Fatal(err)    }    go send(l)    for {        datas := make([]byte, 255)        n, err := l.Read(datas)        if err != nil {            log.Fatal(err)        }    fmt.Println(string(datas[0:n]))    }   }func send(l net.Conn){    sms := make([]byte, 255)    for{        //fmt.Print("请输入要发送的消息:")        _, err := fmt.Scan(&sms)        if err != nil {            fmt.Println("数据输入异常:", err.Error())        }        l.Write(sms)    }}
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.