private void connectCallback(IAsyncResult ar) { try { TcpListener server = (TcpListener)ar.AsyncState; TcpClient client = server.EndAcceptTcpClient(ar); TcpState state = new TcpState(client); this.clientDict.Add(state.ID, state); state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, new AsyncCallback(receiveCallback), state); server.BeginAcceptTcpClient(new AsyncCallback(connectCallback), server); this.Notify?.Invoke($"The client {state.ID} has already connected!"); } catch (Exception ex) { this.Error?.Invoke(ex.Message); } }
private void receiveCallback(IAsyncResult ar) { TcpState state = (TcpState)ar.AsyncState; int readbytes = 0; try { readbytes = state.Stream.EndRead(ar); } catch { readbytes = 0; } if (readbytes == 0) { this.Error?.Invoke($"Client {state.ID} is already disconnect!"); this.clientDict.Remove(state.ID); return; } byte[] buf = new byte[readbytes]; Array.Copy(state.Buffer, 0, buf, 0, readbytes); state.Stream.BeginRead(state.Buffer, 0, state.Buffer.Length, new AsyncCallback(receiveCallback), state); this.Received?.Invoke(buf); }
private void sendCallback(IAsyncResult ar) { TcpState state = (TcpState)ar.AsyncState; state.Stream.EndWrite(ar); }
public void Send(byte[] data, string remote) { TcpState state = this.clientDict[remote]; state.Stream.BeginWrite(data, 0, data.Length, new AsyncCallback(sendCallback), state); }