1. 程式人生 > >golang簡易版聊天室

golang簡易版聊天室

服務端:

package main

import (
    "fmt"
    "net"
)

type info struct {
    conn net.Conn
    name string
}

var ch chan string = make(chan string)
var infos map[string]info = make(map[string]info)

func handle(conn net.Conn) {
    defer conn.Close()

    buf := make([]byte, 100)
    n, _ :
= conn.Read(buf) name := string(buf[:n]) var oneinfo info oneinfo.conn = conn oneinfo.name = name addr := conn.RemoteAddr().String() infos[addr] = oneinfo msg := name + "進入聊天室" ch <- msg fmt.Println(msg) for { n, _ := conn.Read(buf)
if n == 0 { fmt.Printf("%s斷開連線\n", addr) msg = name + "離開聊天室" delete(infos, addr) ch <- msg fmt.Println(msg) return } ch <- name + ":" + string(buf[:n]) } } func send() { for { msg :
= <-ch for _, val := range infos { val.conn.Write([]byte(msg)) } } } func main() { listener, _ := net.Listen("tcp", ":9009") defer listener.Close() go send() for { conn, _ := listener.Accept() fmt.Printf("%s建立連線\n", conn.RemoteAddr().String()) go handle(conn) } }

客戶端:

package main

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

func scandata(conn net.Conn) {
    var x string
    for {
        fmt.Scan(&x)
        if x == "q" {
            os.Exit(0)
        }
        conn.Write([]byte(x))
    }
}
func main() {
    conn, _ := net.Dial("tcp", "127.0.0.1:9009")
    buf := make([]byte, 1024)
    args := os.Args
    conn.Write([]byte(args[1]))
    go scandata(conn)
    for {
        n, _ := conn.Read(buf)
        fmt.Println(string(buf[:n]))
    }
}

截圖:

服務端

客戶端