/// <summary> /// Get Local IP Address /// </summary> /// <returns>String of IP address</returns> protected static string GetLocalIP() { // Loop till local ip while (true) { // Query user WriteGUI("Enter local IP address: "); // Get response string temp = ReadLine(); // Attempt to get local IP try { // Check temp is a string if (String.IsNullOrEmpty(temp)) { throw new ArgumentNullException("IP address", "Invalid IP Address"); } // Get Host Info IPHostEntry tempInfo = Dns.GetHostEntry(temp); // Get Local IP IPAddress tempLocalIP = LAN.GetLocal(tempInfo); // Return ip address return(temp); } catch (ArgumentNullException e) { // Write message WriteGUI(e.Message); } catch (ArgumentException) { // Write user WriteGUI(String.Format("Invalid IP address: {0}", temp)); } catch (Exception e) { // Write exception WriteGUI(e.ToString()); } } }
/// <summary> /// Join a server /// </summary> protected static void Join() { _isExit = false; while (!_isServer) { // Get Local IP Address sLocalIP = GetLocalIP(); // Loop till name accepted while (!_isJoined) { // Attempt to connect to remove device try { // Get username name = GetName(); // Establish connection to socket IPHostEntry ipHostInfo = Dns.GetHostEntry(sLocalIP); // Get Address IPAddress ipAddress = LAN.GetLocal(ipHostInfo); // Get remote endpoint (Ipaddress and port) remoteEP = new IPEndPoint(ipAddress, Values.IntroPort); // Create TCP/IP socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Reset connection connectdone.Reset(); // Connect to remove endpoint client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); // Lock thread until connected connectdone.WaitOne(); // If invalid server if (!_isServer) { // Stop attempting connection // Request new IP break; } // Request to joint server string joinRequest = Strings.command_Join + " " + name; // Send to remote device Server.ToSendIn(joinRequest); Send(client); // Lock thread until sent sendDone.WaitOne(); // Recieve response from remote device // Create state object StateObject state = new StateObject(); // Assign socket state.workSocket = client; // Begin recieving data from remote device client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(RecieveCallback), state); // Lcck thread until data received receiveDone.WaitOne(); // Wait for server queue to be processed processServerDone.WaitOne(Values.serverPollDead); // Handle response if (_isJoined) { // Write Response WriteGUI(name + " accepted to chat."); } else { // Write rejected WriteGUI(name + " rejected."); // retry join connection loop } } catch (SocketException e) { // Alert user WriteGUI("Cannot connect to server at: " + sLocalIP); WriteGUI(e.ToString()); // Is not a valid server _isServer = false; // Break break; } catch (Exception e) { // Write to console WriteGUI(e.ToString()); } } } }
/// <summary> /// Start listening /// </summary> public static void StartListening() { // Data buffer byte[] bytes = new Byte[1024]; // Establish local endpoint for socket IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // Declare IP Address IPAddress ipAddress = LAN.GetLocal(ipHostInfo); // Write IP Address WriteGUI("Connecting to: " + ipAddress.ToString()); // Create end-point IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Values.IntroPort); // Create socket Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind socket to end-point and listen for incoming connection try { // Bind to end-point listener.Bind(localEndPoint); // Listen for listener.Listen(100); // Open socket. Wait for connection WriteGUI("Waiting for a connection . . ."); // While is alive while (!isExit) { // Reeset connection allDone.Reset(); // Accept connection listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Lock thread till timeout. // Poll dead connection if (!allDone.WaitOne(Values.serverPollDead)) { // Check dead connection to client for more than a second bool deadConnection = listener.Poll(1000, SelectMode.SelectRead); // Check no data read bool noData = (listener.Available == 0); // If both, ungracefull disconnect if (deadConnection && noData) { // Write to server WriteGUI("Dead connection at."); // Retry continue; } } } } // If exception catch (ArgumentNullException e) { // Write to console WriteGUI(e.ToString()); } catch (SocketException) { WriteGUI(String.Format("Cannot connect to: {0}:{1}", ipAddress, Values.IntroPort)); } // Write server closed WriteGUI("\nServer closed."); // Write press enter to close WriteGUI("\nPress ENTER to close application. . . ."); ReadLine(); }