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
| package server
import ( "fmt" "net" )
type Server struct { ip string port int OnError func(error) OnMessage func(*AppSession, []byte) }
func New(ip string, port int) *Server { return &Server{ ip: ip, port: port, } }
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 }
go handleClient(server, conn) } }
func handleClient(server *Server, conn net.Conn) { remoteAddr := conn.RemoteAddr()
fmt.Println("客户地址:", remoteAddr)
var buf [10240]byte
for { fmt.Println("等待接收数据...") n, err := conn.Read(buf[0:])
if err != nil { fmt.Println("数据接收错误, ", err) if server.OnError != nil { server.OnError(err) } return }
if server.OnMessage == nil { fmt.Println("错误,未找到数据处理方法!") continue } server.OnMessage(&AppSession{ conn: conn, }, buf[0:n]) } }
|