码迷,mamicode.com
首页 > 其他好文 > 详细

Go简单聊天

时间:2018-09-21 00:38:23      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:fprintf   amp   src   accept   fat   server   fatal   pac   hand   

用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简单聊天

标签:fprintf   amp   src   accept   fat   server   fatal   pac   hand   

原文地址:https://www.cnblogs.com/--just-lbk/p/9684116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!