void AcceptCallBack(IAsyncResult ar) { Socket client = main_socket.EndAccept(ar); main_socket.BeginAccept(AcceptCallBack, null); AsyncObect obj = new AsyncObect(4096); obj.Working_socket = client; connectedClients.Add(client); TxtHistory.Text += string.Format("\n클라이언트(@{0})가 연결되;었습니다.", client.RemoteEndPoint); client.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj); }
void DataReceived(IAsyncResult ar) { AsyncObect obj = (AsyncObect)ar.AsyncState; int received = obj.Working_socket.EndReceive(ar); if (received <= 0) { obj.Working_socket.Close(); return; } string text = Encoding.UTF8.GetString(obj.Buffer); string[] token = text.Split('\x01'); string ip = token[0]; string msg = token[1]; TxtHistory.Text += string.Format("\n[받음]{0}: {1}", ip, msg); for (int i = connectedClients.Count - 1; i >= 0; i--) { Socket socket = connectedClients[i]; if (socket != obj.Working_socket) { try { socket.Send(obj.Buffer); } catch { try { socket.Dispose(); } catch { } connectedClients.RemoveAt(i); } } } obj.ClearBuffer(); obj.Working_socket.BeginReceive(obj.Buffer, 0, 4096, 0, DataReceived, obj); }