public void OnClientConnect(IAsyncResult asyn) { try { m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn); WaitForData(m_workerSocket[m_clientCount]); ++m_clientCount; String str = String.Format("Client # {0} connected", m_clientCount); Invoke(new Action(() => textBoxMsg.Clear())); Invoke(new Action(() => textBoxMsg.AppendText(str))); m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } } public class SocketPacket { public System.Net.Sockets.Socket m_currentSocket; public byte[] dataBuffer = new byte[1024]; } public void WaitForData(System.Net.Sockets.Socket soc) { try { if (pfnWorkerCallBack == null) { pfnWorkerCallBack = new AsyncCallback(OnDataReceived); } SocketPacket theSocPkt = new SocketPacket(); theSocPkt.m_currentSocket = soc;// could be this one!!! soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt); } catch (SocketException se) { MessageBox.Show(se.Message); } } public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket socketData = (SocketPacket)asyn.AsyncState; int iRx = 0; iRx = socketData.m_currentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); Invoke(new Action(() => richTextBoxSendMsg.AppendText(szData))); Invoke(new Action(() => richTextBoxSendMsg.AppendText(Environment.NewLine))); WaitForData(socketData.m_currentSocket); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { MessageBox.Show(se.Message); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)