public void StartListening() { Socket srvr_listenersoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint srvr_ep = new IPEndPoint(IPAddress.Parse(ipAddr), portNumber); srvr_listenersoc.Bind(srvr_ep); srvr_listenersoc.Listen(100); theState = new TCPState(srvr_listenersoc); Console.WriteLine("server set, waiting for connectoin"); try { while (listening) { connectionStablished.Reset(); srvr_listenersoc.BeginAccept(new AsyncCallback(AcceptCallback), srvr_listenersoc); connectionStablished.WaitOne(); Console.WriteLine("connection accepted by server"); } } catch (Exception e) { Console.WriteLine(e.ToString()); StartListening(); } }
private void ConnectionCallback(IAsyncResult ar) { connectionStablished.Set(); Console.WriteLine("Connection stablished"); isConnected = true; TCPState state = (TCPState)ar.AsyncState; StartReceiving(state); }
private void SendCallback(IAsyncResult ar) { try { TCPState state = (TCPState)ar.AsyncState; int bytesSent = state.workSocket.EndSend(ar); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
protected override void ReceiveCallback(IAsyncResult ar) { String content = String.Empty; TCPState state = (TCPState)ar.AsyncState; Socket handler = state.workSocket; int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); content = state.sb.ToString(); int indexOfEOF = content.IndexOf("<EOF>"); if (indexOfEOF > -1) { // A mssg is received content = content.Substring(0, indexOfEOF); if (conIndex != -1) { OnReceivedDataHandler(content); state.sb.Clear(); } else { try { Console.WriteLine("received first packet"); conIndex = Convert.ToInt32(content); OnConnectedHandler(conIndex + ""); } catch { } } // start receiving the next message StartReceiving(state); } else { StartReceiving(state); } } else { // It's theoritically not possible to get here but I put it here just in case StartReceiving(state); } }
public void StartConnection() { Socket cli_connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint srvr_ep = new IPEndPoint(IPAddress.Parse(ipAddr), portNumber); theState = new TCPState(cli_connection); try { connectionStablished.Reset(); cli_connection.BeginConnect(srvr_ep, new AsyncCallback(ConnectionCallback), theState); connectionStablished.WaitOne(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private void AcceptCallback(IAsyncResult ar) { connectionStablished.Set(); Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); TCPState conState = new TCPState(handler); connectionsState.Add(conState); int conIndex = connectionsState.Count - 1; SendMessage_(conIndex + "", conIndex); OnConnectedHandler(conIndex + ""); StartReceiving(conState); }
private void StartReceiving(TCPState state) { state.workSocket.BeginReceive(state.buffer, 0, TCPState.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); }