void AcceptCallback(IAsyncResult ar) { try { Socket client = mainSock.EndAccept(ar); mainSock.BeginAccept(AcceptCallback, null); AsyncObject obj = new AsyncObject(4096); obj.WorkingSocket = client; connectedClients.Add(client); AppendText(richTextBox1, string.Format("{0}", client.RemoteEndPoint)); client.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj); } catch (ObjectDisposedException ex) { MessageBox.Show(ex.Message); } }
void DataReceived(IAsyncResult ar) { try { AsyncObject obj = (AsyncObject)ar.AsyncState; int received = obj.WorkingSocket.EndReceive(ar); string text = Encoding.UTF8.GetString(obj.Buffer); for (int i = connectedClients.Count - 1; i >= 0; i--) { Socket socket = connectedClients[i]; if (socket != obj.WorkingSocket) { try { socket.Send(obj.Buffer); } catch { try { socket.Dispose(); } catch { } connectedClients.RemoveAt(i); } } } if (received <= 0) { obj.WorkingSocket.Close(); return; } obj.ClearBuffer(); obj.WorkingSocket.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj); AppendText(richTextBox1, text); } catch (SocketException ex) { MessageBox.Show(ex.Message, "Cut off Mapo Bridge? ye Shakeya?"); } }