Go简单聊天

Posted --just-lbk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go简单聊天相关的知识,希望对你有一定的参考价值。

用Go简单实现网络通信

其余功能可以在这个模型上继续加,比如增加通信人数,实现聊天

server 端

package main

import (
    "fmt"
    "log"
    "net"
    "os"
)

func broadcaster() {    //功能代完善

}

func handleCoon(conn net.Conn) {
    msg := ""
    for {
        data := make([]byte,1024)
        msg_read,err := conn.Read(data)
        if msg_read == 0 {  //也可以写成  if(msg_read == 0 || err != nil) { } 
            continue
        }else if err != nil {
            fmt.Fprintf(os.Stdout,"readmsg err = %v",err)
            continue
        }

        msg_read_str := string(data[0:msg_read])
        if msg_read_str == "quit" {
            conn.Write([]byte("Exit..."))
            break
        }

        fmt.Println("client msg = ",msg_read_str)

        fmt.Printf("send to client : ")
        fmt.Scan(&msg)

        conn.Write([]byte(msg))
    }

    fmt.Println("client close")
    conn.Close()
}

func main() {

    lis,err := net.Listen("tcp","127.0.0.1:8888")
    if err != nil {
        log.Fatal(err)
    }

    defer lis.Close()
    fmt.Println(lis)
    go broadcaster()

    for {
        conn,err := lis.Accept()
        if err != nil {
            fmt.Fprintf(os.Stdout,"err = %v",err)
            continue
        }

        defer conn.Close()

        go handleCoon(conn)
    }


client 端
package main

import (
    "fmt"
    "net"
    "os"
)

func main() {

    conn,err := net.Dial("tcp","127.0.0.1:8888")
    if err != nil {
        fmt.Fprintf(os.Stdout,"err = %v",err)
    }

    defer conn.Close()

    fmt.Println("connect server sucess")

    var msg string

    for {
        msg = ""
        fmt.Printf("send msg : ")
        fmt.Scan(&msg)

        conn.Write([]byte(msg))

        data := make([]byte,1024)
        msg_read,err := conn.Read(data)
        if msg_read == 0 {    //和上面一样
            fmt.Println("to short for msg")
            continue
        }else if err != nil {
            fmt.Fprintf(os.Stdout,"err = %v",err)
            continue
        }

        msg_read_str := string(data[0:msg_read])

        if msg_read_str == "quit" {
            fmt.Println("server close.....")
            break
        }
        fmt.Println("to you msg = ",msg_read_str)
    }
}

技术分享图片








以上是关于Go简单聊天的主要内容,如果未能解决你的问题,请参考以下文章

用Go语言实现一个简单的聊天机器人

简单的方法来分享/讨论/协作的代码片段?

html5+go+websocket简单实例代码

go语言实现聊天室

golang代码片段(摘抄)

使用 Go 和 ReactJS 构建聊天系统(前言)