/// <summary> /// 连接上服务器 /// </summary> void OnConnect(IAsyncResult asr) { outStream = client.GetStream(); isConnect = true; client.GetStream().BeginRead(byteBuffer, 0, MAX_READ, new AsyncCallback(OnRead), null); NetWorkManager.AddEvent(Protocal.Connect, new ByteBuffer()); }
public void ConnectServer(string ip, int port) { SocketQuit(); //定义套接字类型,必须在子线程中定义 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //连接 IPAddress ipAddress = IPAddress.Parse(ip); IPEndPoint ipEnd = new IPEndPoint(ipAddress, port); serverSocket.ReceiveBufferSize = 8192; serverSocket.NoDelay = true; serverSocket.Connect(ipEnd); //开启一个线程连接,必须的,否则主线程卡死 connectThread = new Thread(new ThreadStart(SocketReceive)); connectThread.Priority = System.Threading.ThreadPriority.Highest; connectThread.Start(); //ZTSceneManager.GetInstance().StartCoroutine(OnReceiveCoroutine()); //serverSocket.BeginReceive(clientBuffer, 0, this.clientBuffer.Length, SocketFlags.None, // new System.AsyncCallback(clientReceive), this.serverSocket); NetWorkManager.AddEvent(Protocal.Connect, new ByteBuffer()); }
/// <summary> /// 接收到消息 /// </summary> /// <param name="ms"></param> void OnReceivedMessage(MemoryStream ms) { BinaryReader r = new BinaryReader(ms); byte[] message = r.ReadBytes((int)(ms.Length - ms.Position)); ByteBuffer buff = new ByteBuffer(message); NetWorkManager.AddEvent(Protocal.NetMessage, buff); }
/// <summary> /// 丢失链接 /// </summary> void OnDisconnected(DisType dis, string msg) { Close(); //关掉客户端链接 int protocal = 0; ByteBuffer buffer = new ByteBuffer(); if (dis == DisType.Disconnect) { protocal = Protocal.Disconnect; } else { protocal = Protocal.Exception; buffer.WriteString("Connection was closed by the server:>" + msg + ", Distype:>" + dis); } NetWorkManager.AddEvent(protocal, buffer); }
/// <summary> /// 接收到消息 /// </summary> void OnReceive(byte[] bytes) { ByteBuffer buff = new ByteBuffer(bytes); NetWorkManager.AddEvent(Protocal.NetMessage, buff); }