1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| package server
import ( "fmt" "net" "time" )
type Server struct { ip string port int clientCounter int64 OnError func(error) OnMessage func(*AppSession, []byte) }
func New(ip string, port int) *Server { return &Server{ ip: ip, port: port, clientCounter: 0, } }
func (server *Server) Start() { localAddress, _ := net.ResolveTCPAddr("tcp4", fmt.Sprintf("%s:%d", server.ip, server.port))
tcpListener, err := net.ListenTCP("tcp", localAddress)
if err != nil { fmt.Println("监听出错, ", err) if server.OnError != nil { server.OnError(err) } return }
defer tcpListener.Close()
for { fmt.Println("等待客户连接...")
conn, err := tcpListener.Accept()
if err != nil { fmt.Println("客户连接失败, ", err) if server.OnError != nil { server.OnError(err) } continue }
server.clientCounter++
appSession := &AppSession{ ID: server.clientCounter, conn: conn, activeDateTime: time.Now(), }
go handleClient(server, appSession) } }
func handleClient(server *Server, session *AppSession) { remoteAddr := session.conn.RemoteAddr()
fmt.Println("客户[", session.ID, "]地址:", remoteAddr)
for { fmt.Println("等待接收客户[", session.ID, "]的数据...", session.activeDateTime)
bytes, err := session.Read()
if err != nil { fmt.Println("客户[", session.ID, "]数据接收错误, ", err) if server.OnError != nil { server.OnError(err) } return }
if server.OnMessage == nil { fmt.Println("错误,未找到数据处理方法!") continue } server.OnMessage(session, bytes) } }
|