2016-07-23 4 views
1

私は自分のパソコンから他のパソコンに接続しようとしています。私は自宅にいるものをインターネットに接続しています。だから私は、プログラムMyIpAdressで他のPCをチェックし、それは次のようである:38.xx.xx.xx. そして、私はこのプログラムを持っています。サーバー:ローカルではない他のコンピュータに接続する

public delegate void StatusChangedHandler(object sender, StatusChangedEventArgs e); 

    public class StatusChangedEventArgs : EventArgs 
    { 
     // This will store our only parameter/event argument, which is the event message 
     private string EventMsg; 

     // We need to define this property in order to retrieve the message in the event handler, back in Form1.cs 
     public string EventMessage 
     { 
      get 
      { 
       return EventMsg; 
      } 
     } 

     // The constructor will set the message 
     public StatusChangedEventArgs(string strEventMsg) 
     { 
      EventMsg = strEventMsg; 
     } 
    } 

    class Monitor 
    { 
     // Will store the IP address passed to it 
     IPAddress ipAddress; 

     // The constructor sets the IP address to the one retrieved by the instantiating object 
     public Monitor(IPAddress address) 
     { 
      ipAddress = address; 
     } 

     // Declare the event that we'll fire later 
     public event StatusChangedHandler StatusChangedEvent; 
     // The thread that will hold the connection listener 
     private Thread thrListener; 
     // The TCP object that listens for connections 
     private TcpListener tlsServer; 
     // The thread that will send information to the client 
     private Thread thrSender; 
     // Will tell the while loop to keep monitoring for connections 
     bool ServRunning = false; 

     public void StartMonitoring() 
     { 
      // Get the IP of the first network device, however this can prove unreliable on certain configurations 
      IPAddress ipaLocal = ipAddress; 
      if (tlsServer == null) 
      { 
       // Create the TCP listener object using the IP of the server and the specified port 
       tlsServer = new TcpListener(ipaLocal, 1986 ); 
      } 
      // Start the TCP listener and listen for connections 
      tlsServer.Start(); 

      // The while loop will check for true in this before checking for connections 
      ServRunning = true; 

      // Start the new tread that hosts the listener 
      thrListener = new Thread(KeepListening); 
      thrListener.Start(); 
     } 

     private void KeepListening() 
     { 
      TcpClient tclServer; 
      // While the server is running 
      while (ServRunning == true) 
      { 
       // Accept a pending connection 
       tclServer = tlsServer.AcceptTcpClient(); 
       // Start a new thread where our new client who just connected will be managed 
       thrSender = new Thread(new ParameterizedThreadStart(AcceptClient)); 
       // The thread calls the AcceptClient() method 
       thrSender.Start(tclServer); 
      } 
     } 

     // Occures when a new client is accepted 
     private void AcceptClient(object newClient) 
     { 
      // Set the argument/parameter to a message explaining what just happened 
      StatusChangedEventArgs evArg = new StatusChangedEventArgs("A client was successfully accepted."); 
      // Fire the event because a new client was accepted 
      StatusChangedEvent(this, evArg); 
     } 
    } 

をしかし、私はテキストボックスにipadressで埋める場合:38.xxx.xxx.xx
をさせていただきますこのエラーが表示されます:

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll Additional information: The requested address is not valid in its context

ローカルIPアドレスしか表示されませんか?
しかし、それを変更する方法、それはまた、ローカルIpadressesを見つけることはありません?

そして、これはクライアントアプリケーションです:

tcpServer.Connect(IPAddress.Any、1986):だから私はこの行を変更フォーム {

private string UserName = "Unknown"; 
    private StreamWriter swSender; 
    private StreamReader srReceiver; 
    private TcpClient tcpServer; 
    // Needed to update the form with messages from another thread 
    private delegate void UpdateLogCallback(string strMessage); 
    // Needed to set the form to a "disconnected" state from another thread 
    private delegate void CloseConnectionCallback(string strReason); 
    private Thread thrMessaging; 
    private IPAddress ipAddr; 
    private bool Connected; 

    public Form1() 
    { 
     Application.ApplicationExit += new EventHandler(OnApplicationExit); 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     // If we are not currently connected but awaiting to connect 
     if (Connected == false) 
     { 
      // Initialize the connection 
      InitializeConnection(); 
     } 
     else // We are connected, thus disconnect 
     { 
      CloseConnection("Disconnected at user's request."); 
     } 
    } 

    private void ReceiveMessages() 
    { 
     // Receive the response from the server 
     srReceiver = new StreamReader(tcpServer.GetStream()); 
     // If the first character of the response is 1, connection was successful 
     string ConResponse = srReceiver.ReadLine(); 
     // If the first character is a 1, connection was successful 
     if (ConResponse[0] == '1') 
     { 
      // Update the form to tell it we are now connected 
      this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Connected Successfully!" }); 
     } 
     else // If the first character is not a 1 (probably a 0), the connection was unsuccessful 
     { 
      string Reason = "Not Connected: "; 
      // Extract the reason out of the response message. The reason starts at the 3rd character 
      Reason += ConResponse.Substring(2, ConResponse.Length - 2); 
      // Update the form with the reason why we couldn't connect 
      this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason }); 
      // Exit the method 
      return; 
     } 
     // While we are successfully connected, read incoming lines from the server 
     while (Connected) 
     { 
      // Show the messages in the log TextBox 
      this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() }); 
     } 
    } 
    private void InitializeConnection() 
    { 
     // Parse the IP address from the TextBox into an IPAddress object 
     ipAddr = IPAddress.Parse(txtServerIP.Text); 
     // Start a new TCP connections to the chat server 
     tcpServer = new TcpClient(); 
     tcpServer.Connect(IPAddress.Any, 1986); 

     // Helps us track whether we're connected or not 
     Connected = true; 
     // Prepare the form 
     UserName = txtUserName.Text; 

     // Disable and enable the appropriate fields 
     txtServerIP.Enabled = false; 
     txtUserName.Enabled = false; 
     txtMessage.Enabled = true; 
     btnSend.Enabled = true; 
     btnConnect.Text = "Disconnect"; 

     // Send the desired username to the server 
     swSender = new StreamWriter(tcpServer.GetStream()); 
     swSender.WriteLine(txtUserName.Text); 
     swSender.Flush(); 

     // Start the thread for receiving messages and further communication 
     thrMessaging = new Thread(new ThreadStart(ReceiveMessages)); 
     thrMessaging.Start(); 
    } 
    private void UpdateLog(string strMessage) 
    { 
     // Append text also scrolls the TextBox to the bottom each time 
     txtLog.AppendText(strMessage + "\r\n"); 
    } 

    private void btnSend_Click(object sender, EventArgs e) 
    { 
     SendMessage(); 
    } 

    private void SendMessage() 
    { 
     if (txtMessage.Lines.Length >= 1) 
     { 
      swSender.WriteLine(txtMessage.Text); 
      swSender.Flush(); 
      txtMessage.Lines = null; 
     } 
     txtMessage.Text = ""; 
    } 
    // Closes a current connection 
    private void CloseConnection(string Reason) 
    { 
     // Show the reason why the connection is ending 
     txtLog.AppendText(Reason + "\r\n"); 
     // Enable and disable the appropriate controls on the form 
     txtServerIP.Enabled = true; 
     txtUserName.Enabled = true; 
     txtMessage.Enabled = false; 
     btnSend.Enabled = false; 
     btnConnect.Text = "Connect"; 

     // Close the objects 
     Connected = false; 
     swSender.Close(); 
     srReceiver.Close(); 
     tcpServer.Close(); 
    } 
    public void OnApplicationExit(object sender, EventArgs e) 
    { 
     if (Connected == true) 
     { 
      // Closes the connections, streams, etc. 
      Connected = false; 
      swSender.Close(); 
      srReceiver.Close(); 
      tcpServer.Close(); 
     } 
    } 
} 

公共部分クラスをForm1 ;

が、私は、サーバーアプリケーションを実行する場合、私はこのエラーを取得します:

私はクライアントによって同じエラーを取得する:

型「System.Net.Sockets.SocketException」の未処理の例外が発生した

System.dllの

追加情報に:要求されたアドレスは

いただきありがとうございます、そのコンテキストで有効ではありません

私はあなたに2つの画像を示します:これはサーバーアプリケーションです。私はこのように、クライアントアプリケーションのコードを変更した場合 enter image description here

そして:

tcpServer.Connect(ip-addrで、1986)それは enter image description here

これは、クライアントアプリ、それdoesntのが仕事であるに動作します;それから私は、このエラーが発生します。

追加情報:接続の試みは、接続先が適切に一定期間後に応答しなかったため、接続されたホストが応答に失敗したため、または確立された接続が失敗した失敗した

しかし、私はすることができます私はその後、変更しなければならないもの

private void InitializeConnection() 
     { 
      // Parse the IP address from the TextBox into an IPAddress object 
      ipAddr = IPAddress.Parse(txtServerIP.Text); 
      // Start a new TCP connections to the chat server 
      tcpServer = new TcpClient(); 
      tcpServer.Connect(IPAddress.Any, 1986); 

      // Helps us track whether we're connected or not 
      Connected = true; 
      // Prepare the form 
      UserName = txtUserName.Text; 

      // Disable and enable the appropriate fields 
      txtServerIP.Enabled = false; 
      txtUserName.Enabled = false; 
      txtMessage.Enabled = true; 
      btnSend.Enabled = true; 
      btnConnect.Text = "Disconnect"; 

      // Send the desired username to the server 
      swSender = new StreamWriter(tcpServer.GetStream()); 
      swSender.WriteLine(txtUserName.Text); 
      swSender.Flush(); 

      // Start the thread for receiving messages and further communication 
      thrMessaging = new Thread(new ThreadStart(ReceiveMessages)); 
      thrMessaging.Start(); 
     } 

:クライアントプログラムでは、他のPC

をピン私はこれを持っていますか?

+0

いただきありがとうございます。投稿を編集します。 – SavantCode

+0

清算のためです。サーバーアプリケーションを実行すると動作します。しかし、クライアントアプリケーションを実行すると、それは – SavantCode

+0

私は投稿を編集しません。私が変更しなければならないことをコードに表示できますか? – SavantCode

答えて

0

おそらく、両方のPCのアプリケーションのファイアウォールのポートでTCP接続を許可する必要があります。ネットワークとの接続が許可されていることを確認してください。

+0

誰かいくつかの提案?ありがとうございました – SavantCode

関連する問題