【问题标题】:connect to other computer that is not local连接到非本地的其他计算机
【发布时间】:2016-07-23 22:40:30
【问题描述】:

我尝试从我的电脑连接到我家中的其他电脑,并且两者都连接到互联网。所以我用程序 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);
        }
    }

但如果我在文本框中填写 IP 地址:38.xxx.xxx.xx,
我会收到这个错误:

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

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

这是客户端应用程序:

公共部分类 Form1 : Form {

    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.dll 中出现“System.Net.Sockets.SocketException”类型的未处理异常

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

谢谢

我给你看两张图片:这是服务器应用程序。这样可行

这是客户端应用程序,它不起作用:

如果我更改客户端应用程序中的代码,如下所示:

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

那我要改变什么?

【问题讨论】:

  • 感谢您的评论。我编辑帖子
  • 为了清晰起见。如果我运行服务器应用程序,它可以工作。但是如果我运行客户端应用程序它不会
  • 我编辑帖子。您能否在代码中显示我必须更改的内容。
  • @X。嗨,你能编辑我的代码示例吗?因为我不明白你的意思。谢谢

标签: c# multithreading


【解决方案1】:

也许您必须在防火墙中的端口上为两台 PC 上的应用程序允许 TCP 连接。确保允许进出网络的连接。

【讨论】:

  • 有人有什么建议吗?谢谢
猜你喜欢
  • 2019-06-27
  • 2020-10-03
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
相关资源
最近更新 更多