/// <summary> /// A function used when we receive a callback and can begin reading data sent /// </summary> /// <param name="ar"></param> public static void ReceiveCallback(IAsyncResult ar) { SocketState ss = (SocketState)ar.AsyncState; try { //Ends the reading operation so we can save it and process the data. int bytesRead = ss.theSocket.EndReceive(ar); // If the socket is still open if (bytesRead > 0) { //Save the data for processing. string theMessage = Encoding.UTF8.GetString(ss.messageBuffer, 0, bytesRead); // Append the received data to the growable buffer. // It may be an incomplete message, so we need to start building it up piece by piece ss.sb.Append(theMessage); //Send to the callback. ss.callBack(ss); } else { ss.theSocket.Disconnect(false); ss.shutdownSocket(); ss.callBack = null; return; } // Continue the "event loop" that was started on line 154. // Start listening for more parts of a message, or more new messages //ss.theSocket.BeginReceive(ss.messageBuffer, 0, ss.messageBuffer.Length, SocketFlags.None, ReceiveCallback, ss); } catch (Exception ex) { //Console.WriteLine("Receive + " + ex.Message); //IPAddress ipAddress = IPAddress.None; //Socket tempsock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //SocketState d = new SocketState(tempsock, -1); //Send to the client our failed socketstate. (In the snake client case this should be first contact...) //ss.callBack(d); ss.shutdownSocket(); } }
/// <summary> /// Used to begin sending data by client /// </summary> /// <param name="socket"></param> /// <param name="data"></param> public static void Send(SocketState socket, string data) { //try catch, will help indicate if a server randomly disconnected. try { //Save the given data to a byte and send it byte[] totalByte = Encoding.UTF8.GetBytes(data); socket.theSocket.BeginSend(totalByte, 0, totalByte.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket); } catch (Exception e) { Console.WriteLine("Send Exception"); if (socket.getFailStatus() == true) { socket.shutdownSocket(); } else { } } }