/// <summary> /// 关闭服务器 /// </summary> public virtual void CloseServer() { try { if (reciveTh != null) { reciveTh.Abort(); reciveTh = null; } if (sendTh != null) { sendTh.Abort(); sendTh = null; } if (server != null) { server.Close(); server = null; NetworkTools.PrintMessage("关闭服务器!"); } } catch (Exception e) { Debug.LogError(e.ToString()); } }
public BattleServer() { //测试 //players.Add("10.8.44.126"); //players.Add("10.8.44.10"); //players.Add("10.8.44.117"); StartServer(); NetworkTools.PrintMessage("开始战斗服务器"); }
/// <summary> /// 启动服务器 /// </summary> public virtual void StartServer() { server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(new IPEndPoint(IPAddress.Parse(NetworkTools.GetLocalIP()), NetworkConstent.UDPServerPort));//绑定端口号和IP server.IOControl((int)NetworkConstent.SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); NetworkTools.PrintMessage("服务器已启动:" + NetworkTools.GetLocalIP() + " -- " + NetworkConstent.UDPServerPort); reciveTh = new Thread(ReciveMsg); reciveTh.Start(); }
/// <summary> /// 接收发送给本机ip对应端口号的数据报 /// </summary> protected virtual void ReciveMsg() { try { NetworkTools.PrintMessage("客户端开始接收消息"); byte[] buffer = new byte[1024]; while (true) { EndPoint point = new IPEndPoint(IPAddress.Any, 0); //用来保存发送方的ip和端口号 int length = server.ReceiveFrom(buffer, ref point); //接收数据报 byte[] messageBytes = buffer.Skip(0).Take(length).ToArray(); //截取数组,从第0位开始,截取length长度的 //NetworkTools.PrintMessage("接收到消息" + messageBytes.Length); NetworkMessage me = NetworkMessage.GetMessage(messageBytes); //Debug.Log("收到客户端信息; " + me.type); NetworkManager._Instance.AddMessage(me); } } catch (Exception e) { //Debug.LogError(e.ToString()); } }