连接到非本地的其他计算机

时间:2016-07-23 11:29:59

标签: c# multithreading

我尝试从我的电脑连接到家里的其他电脑,并且都连接到互联网。所以我用MyIpAdress程序查看另一台电脑,它就像: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
我会收到这个错误:

  

未处理的类型' System.Net.Sockets.SocketException'   发生在System.dll中   附加信息:请求的地址在其上下文中无效

所以它只能看到本地ipAdresses?
但是如何改变呢,它也找不到本地的Ipadresses?

这是客户端应用程序:

公共部分类Form1:表单     {

    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();
        }
    }
}

所以我改变了这一行:

tcpServer.Connect(IPAddress.Any,1986);

但如果我运行服务器应用程序,我将收到此错误:

我得到了与客户相同的错误:

未处理的类型' System.Net.Sockets.SocketException'发生在System.dll

附加信息:请求的地址在其上下文中无效

谢谢

我向您展示了两个图像:这是服务器应用程序。这样可行 enter image description here

这是客户端应用,不起作用: enter image description here

如果我更改客户端应用中的代码,请执行以下操作:

tcpServer.Connect(ipAddr,1986);然后我会得到这个错误:

其他信息:连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接主机无法响应而建立连接失败

但我可以锁定其他电脑

在客户端程序中,我有这个:

  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();
        }

我必须改变什么?

1 个答案:

答案 0 :(得分:0)

也许您必须允许防火墙端口上的TCP连接用于两台PC上的应用程序。确保允许与网络建立连接。