private void AcceptCallBack(IAsyncResult ar) { Socket client = ServerSocket.EndAccept(ar); ServerSocket.BeginAccept(AcceptCallBack, null); AsyincObject obj = new AsyincObject(); obj.WorkingSocket = client; ClientSockets.Add(client); obj.ID = ClientSockets.Count; client.BeginReceive(obj.Buffer, 0, obj.BufferSize, SocketFlags.None, ReceivedDataFromClient, obj); }
private void ReceivedDataFromClient(IAsyncResult ar) { AsyincObject obj = (AsyincObject)ar.AsyncState; int num = obj.WorkingSocket.EndReceive(ar); string msgFromClient = Encoding.UTF8.GetString(obj.Buffer).Trim('\0'); string msg = "From {" + obj.ID + "}" + " :" + msgFromClient; Debug.Write(msg); //byte[] sendMsgFromServer = new byte[obj.BufferSize]; msg = "{" + obj.ID + "} : ACK"; obj.WorkingSocket.Send(Encoding.UTF8.GetBytes(msg)); obj.ClearBuffer(); try { obj.WorkingSocket.BeginReceive(obj.Buffer, 0, obj.BufferSize, SocketFlags.None, ReceivedDataFromClient, obj); } catch (Exception e) { int i = 0; foreach (Socket s in ClientSockets) { if (!s.Connected) { ClientSockets.RemoveAt(i); break; } i++; } Debug.WriteLine("Num of Client : " + ClientSockets.Count); } }