go语言网络编程,先从聊天室开始:
/** * Created by Vicky.H on 13-12-6. * eclipser@163.com */ package main import ( "fmt" "net" "strconv" "bytes" _ "bufio" _ "strings" ) var m map[string]*net.Conn func main() { m = make(map[string]*net.Conn, 10) listener ,err := net.Listen("tcp", ":8080") if err != nil { fmt.Errorf(err.Error()) return } defer listener.Close() index := 0 for { conn, err := listener.Accept() if err != nil { fmt.Errorf(err.Error()) return } name := "用户:" + strconv.Itoa(index) defer connCloseHandler(name, conn) m[name] = &conn index++ go connHandler(name, conn) } } func connCloseHandler(name string, conn net.Conn) { conn.Close() delete(m, name) for key := range(m) { if key != name { (*(m[key])).Write(bytes.NewBufferString(name + " 离开房间\n").Bytes()) (*(m[key])).Write(bytes.NewBufferString("当前房间人数:" + strconv.Itoa(len(m)) + "\n").Bytes()) } } } func connHandler (name string, conn net.Conn) { conn.Write(bytes.NewBufferString("当前房间人数:" + strconv.Itoa(len(m)) + "\n").Bytes()) for key := range(m) { if key != name { (*(m[key])).Write(bytes.NewBufferString(name + " 进入房间\n").Bytes()) } } for { buf := make([]byte,1024) conn.Read(buf) msg := string(buf) conn.Write(bytes.NewBufferString("我说: " + msg).Bytes()) for key := range(m) { if key != name { (*(m[key])).Write(bytes.NewBufferString(name + " 说: " + msg).Bytes()) } } } }
运行:go run main.go
测试结果
有疑问加站长微信联系(非本文作者)