0

我正在尝试在手持设备和 PC 之间建立通信。

对于客户端,我有以下代码:

    public void connect(string IPAddress, int port)
    {
                // Connect to a remote device.
        try
        {
           IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 10 });
           IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
           // Create a TCP/IP socket.
           client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           // Connect to the remote endpoint.
           client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
           if (connectDone.WaitOne()){
                 //do something..
           }
           else{
                 MessageBox.Show("TIMEOUT on WaitOne");
           }
        }
        catch(Exception e){
                 MessageBox.Show(e.Message);
        }
      }

我的问题是,当我在 PC 上运行它们时,它们可以正常通信,但是 SmartDevice 项目中的相同代码无法连接到 PC 上运行的服务器,这给了我这个错误:

System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or stablished connection failed 
because connected host has failed to respond

我错过了什么?

注意:IPAddress 是硬编码在代码中的


编辑: 这是我从 MSDN 示例中获取的另一个代码。这也不起作用,它说它无法阅读。本例的服务端代码与示例相同,客户端代码有一个修改:

private void button1_Click(object sender, EventArgs e)
{
    // In this code example, use a hard-coded
    // IP address and message.
    string serverIP = "192.168.1.10";//HERE IS THE DIFERENCE
    string message = "Hello";
    Connect(serverIP, message);
}

提前感谢您的帮助!

4

1 回答 1

1

对于我的“移动设备”客户端,我使用以下命令将数据发送到“PC”主机:

private void Send(string value) {
  byte[] data = Encoding.ASCII.GetBytes(value);
  try {
    using (TcpClient client = new TcpClient(txtIPAddress.Text, 8000)) {
      NetworkStream stream = client.GetStream();
      stream.Write(data, 0, data.Length);
    }
  } catch (Exception err) {
    // Log the error
  }
}

对于主机,您最好使用线程或BackgroundWorker,您可以让TcpListener对象坐下来等待:

private void Worker_TcpListener(object sender, DoWorkEventArgs e) {
  BackgroundWorker worker = (BackgroundWorker)sender;
  do {
    string eMsg = null;
    int port = 8000;
    try {
      _listener = new TcpListener(IPAddress.Any, port);
      _listener.Start();
      TcpClient client = _listener.AcceptTcpClient(); // waits until data is avaiable
      int MAX = client.ReceiveBufferSize;
      NetworkStream stream = client.GetStream();
      Byte[] buffer = new Byte[MAX];
      int len = stream.Read(buffer, 0, MAX);
      if (0 < len) {
        string data = Encoding.UTF8.GetString(buffer);
        worker.ReportProgress(len, data.Substring(0, len));
      }
      stream.Close();
      client.Close();
    } catch (Exception err) {
      // Log your error
    }
    if (!String.IsNullOrEmpty(eMsg)) {
      worker.ReportProgress(0, eMsg);
    }
  } while (!worker.CancellationPending);
}
于 2012-07-25T17:42:49.460 回答