// Start waiting for data from the client public void WaitForData(System.Net.Sockets.Socket soc) { try { if (BeginReceiveCallBack == null) { // Specify the call back function which is to be // invoked when there is any write activity by the // connected client BeginReceiveCallBack = new AsyncCallback(OnDataReceived); } SocketPacket theSocPkt = new SocketPacket(); theSocPkt.currentSocket = soc; // Start receiving any data written by the connected client // asynchronously soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, BeginReceiveCallBack, theSocPkt); } catch (Exception ex) { ServerException(this, new ExceptionEventArgs(ex)); } }
/// <summary> /// Ожидание получения данных. /// </summary> public void WaitForData() { try { if (BeginReceiveCallBack == null) { BeginReceiveCallBack = new AsyncCallback(OnDataReceived); } SocketPacket theSocPkt = new SocketPacket(); theSocPkt.currentSocket = ClientSocket; // Start listening to the data asynchronously ClientSocket.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, BeginReceiveCallBack, theSocPkt); } catch (Exception ex) { ClientException(this, new ExceptionEventArgs(ex)); } }
public void OnDataReceived(IAsyncResult asyn) { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; try { int byteReceived = theSockId.currentSocket.EndReceive(asyn); if (byteReceived > 0) { string szData = Encoding.UTF8.GetString(theSockId.dataBuffer, 0, byteReceived); MessageReceived(this, new ReceivedEventArgs(szData)); } WaitForData(); } catch (Exception ex) { ClientException(this, new ExceptionEventArgs(ex)); if (!theSockId.currentSocket.Connected) { Disconnected(this, EventArgs.Empty); } } }
// This the call back function which will be invoked when the socket // detects any client writing of data on the stream public void OnDataReceived(IAsyncResult asyn) { SocketPacket socketData = (SocketPacket)asyn.AsyncState; try { // Complete the BeginReceive() asynchronous call by EndReceive() method // which will return the number of characters written to the stream // by the client int byteReceived = socketData.currentSocket.EndReceive(asyn); if (byteReceived > 0) { string szData = Encoding.UTF8.GetString(socketData.dataBuffer, 0, byteReceived); //Socket clientSocket = FindClientSocket(socketData.m_currentSocket); Socket clientSocket = socketData.currentSocket; if (clientSocket != null) { AsyncClient client = new AsyncClient(clientSocket); MessageReceived(this, new ServerReceivedEventArgs(client, szData)); } } // Continue the waiting for data on the Socket WaitForData(socketData.currentSocket); } catch (Exception ex) { // Очистка списка и словаря клиентов. AsyncClient asyncClient = AsyncClientsDict[socketData.currentSocket]; Clients.Remove(asyncClient); AsyncClientsDict.Remove(socketData.currentSocket); ServerException(this, new ExceptionEventArgs(ex)); } }