// This is broadcast server demo work with the echo_client. // usage: // cd src/github.com/funny/link // go generate channel.go // go run example/echo/broadcast.go func main() { var addr string flag.StringVar(&addr, "addr", ":10010", "echo server address") flag.Parse() server, err := link.Serve("tcp", addr, link.Async(1024, link.Packet(2, 1024*1024, 1024, binary.LittleEndian, TestCodec{}))) if err != nil { panic(err) } println("server start:", server.Listener().Addr().String()) channel := link.NewUint64Channel() go func() { for range time.Tick(time.Second * 2) { now := "from channel: " + time.Now().Format("2006-01-02 15:04:05") channel.Fetch(func(session *link.Session) { session.Send(now) }) } }() for { session, err := server.Accept() if err != nil { break } go func() { addr := session.Conn().RemoteAddr().String() println("client", addr, "connected") channel.Put(session.Id(), session) for { var msg string if err := session.Receive(&msg); err != nil { break } println(addr, "say:", msg) channel.Fetch(func(session *link.Session) { session.Send("from " + addr + ": " + string(msg)) }) } println("client", addr, "closed") channel.Remove(session.Id()) }() } }
package global import ( // "runtime" "github.com/funny/link" . "tools" "tools/codecType" "tools/dispatch" "tools/gc" ) var ( PackCodecType_UnSafe link.CodecType = link.Packet(4, 1024*1024, 4096, link.LittleEndian, codecType.NetCodecType{}) PackCodecType_Safe link.CodecType = link.ThreadSafe(PackCodecType_UnSafe) PackCodecType_Async link.CodecType = link.Async(4096, PackCodecType_UnSafe) ) //服务器启动 func Startup(serverName string, logFile string, stopServerFunc func()) { // runtime.GOMAXPROCS(runtime.NumCPU()) // 开启Log记录 SetLogFile(logFile) SetLogPrefix(serverName) // 信号量监听 go SignalProc(stopServerFunc) // 开启GC及系统环境信息监测 gc.SysRoutine()