private void ReceiveCallback(IAsyncResult ar) { Socket socket = (Socket)ar.AsyncState; /* create a try catch block here to handle a connection being closed unexpectedly. */ try { int received = socket.EndReceive(ar); /* this gets the byte length of received data, if no data is received we close the client.*/ if (received <= 0) { CloseClient(); /*this closes the client of number x*/ } else { byte[] databuffer = new byte[received]; Array.Copy(_buffer, databuffer, received); /* this part copies the data buffer into a new buffer of the length of the received data */ //HandleNetworkInformation; ServerHandleNetworkData.HandleNetworkInformation(index, databuffer); socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket); //This opens the server to receiving data, again. } } catch { CloseClient(); //This will catch the error and close that connection. } }
private void networkSetup() { ServerHandleNetworkData.InitializeNetworkPackages(); ClientHandleNetworkData.InitializeNetworkPackages(); toolStripCapsStatus.Text = KeyText(); toolStripModeStatus.Text = ServerMode; switch (Settings.Mode) { case "Server": Server.SetupServer(); break; case "Client": Client.ConnectToServer(); break; } }