Golang a simple chat program based on TCP/IP

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

Server.go

Package Mainimport ("FMT" "IO" "NET" "OS" "strings") func main () {addr, err: = Net. RESOLVETCPADDR ("TCP", ": 4040") Checkerr (Err) Listen, err: = Net. LISTENTCP ("tcp", addr) Checkerr (err) fmt. PRINTLN ("Start server ...") for {conn, err: = Listen. Accept () Checkerr (err) go Handle (conn)//each time a connection is established, it is processed in a separate thread}}const buflength = 128var users map[string]net. Conn = Make (map[string]net. Conn, func Handle (Conn net). Conn) {Conn. Write ([]byte ("Welcome to 2B Chat Group ~")) for {data: = make ([]byte, 0)//here do an input buffer to avoid data being too long to read to incomplete data buf: = Make ([]byte, buflength) for {n, ERR: = conn. Read (BUF) if err! = Nil && Err! = Io. EOF {checkerr (err)}data = append (data, buf[:n] ...) if n! = buflength {break}}cmd: = strings. Split (String (data), "|") Fmt. Println ("command:", cmd) switch cmd[0] {case "Nick": FMT. PRINTLN ("Registered name:" + cmd[1]) users[cmd[1]] = conncase "Say": For K, V: = Range users {if k! = cmd[1] {fmt. Println ("give" + K + "Send message:" + cmd[2]) v.write ([]byte (cmd[1] + ": [" + cmd[2] + "]"))}}}}}func Checkerr (err error) {if Err! = N Il {fmt. PRINTLN (ERR) OS. Exit(-1)}} 

Client.go

package mainimport ("fmt""io""net""os")var nick string = ""func main() {addr, err := net.ResolveTCPAddr("tcp", ":4040")checkErr(err)conn, err := net.DialTCP("tcp", nil, addr)checkErr(err)// 读取提示data := make([]byte, 1024)conn.Read(data)fmt.Println(string(data))// 输入昵称fmt.Print("输入昵称:")fmt.Scanf("%v", &nick)fmt.Println("Hello " + nick)conn.Write([]byte("nick|" + nick))go Handle(conn)for {someTex := ""fmt.Scanf("%v", &someTex)conn.Write([]byte("say|" + nick + "|" + someTex))}}const BufLength = 128func Handle(conn net.Conn) {for {data := make([]byte, 1024)buf := make([]byte, BufLength)for {n, err := conn.Read(buf)if err != nil && err != io.EOF {checkErr(err)}data = append(data, buf[:n]...)if n != BufLength {break}}fmt.Println(string(data))}}func checkErr(err error) {if err != nil {fmt.Println(err)os.Exit(-1)}}
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.