Search code examples
c#socketscompact-frameworkwindows-ce

Socket connection in CF 3.5 C#


I am trying to establish a communication between a handheld and a PC.

I have the following code, for the client:

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

My problem is that when I run both of them in a pc they communicate fine, but the same code in a SmartDevice Project doesn't connect with the Server which is running on the PC and it give me this error:

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

What am I missing?

NOTE: The IPAddress is hard coded inside the code


EDIT: here is another code which I take from a MSDN example. This don't work either, it says that it not possible to read. The server code in this case is the same as the example, the client code have a modification:

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

Thanks in advance for any help!


Solution

  • For my "mobile device" client, I send data to the "PC" host using this:

    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
      }
    }
    

    For the host, you're best to use a thread or BackgroundWorker where you can let a TcpListener object sit and wait:

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