连接到C#Server的Java客户端:连接超时

时间:2017-07-15 09:51:50

标签: java c# android sockets

我正在尝试将两个Android设备连接到c#-server,我总是得到连接超时。 java代码很简单:

Socket socket = new Socket(mAddress, PORT);

如果我在电脑上启动java服务器,那么连接成功。所以它不是网络/防火墙问题。 但我的c#-server只是不接受任何连接,代码:

private TcpListener serverSocket;
private TcpClient clientSocket1;
private TcpClient clientSocket2;

    private void Form1_Load(object sender, EventArgs e)
    {
        serverSocket = new TcpListener(IPAddress.Any, port);
        clientSocket1 = default(TcpClient);
        clientSocket2 = default(TcpClient);
        serverSocket.Start();

        clientListenerThread = new Thread(wait4Clients);
        clientListenerThread.Start();

    }
    private void wait4Clients()
    {
        logToConsole("Clientlistener started");
        clientSocket1 = serverSocket.AcceptTcpClient();
        logToConsole("Client No 1 started!");

        clientSocket2 = serverSocket.AcceptTcpClient();
        logToConsole("Client No 2 started!");
    }

我也尝试过System.Net.Sockets.Socket而不是System.Net.Sockets.TcpClient,也没用。

非常感谢

编辑:似乎代码完全没问题。如果我通过Visual Studio运行exe而不是调试模式,一切正常。因此,调试模式会以某种方式阻止服务器套接字正常工作。任何想法为什么会这样?

1 个答案:

答案 0 :(得分:0)

// TCP Server C#, look at [msdn][1]
try
{
  // Set the TcpListener on port 8080 of Any IP Address.
  TcpListener server = new TcpListener(IPAddress.Any, 8080);

  // Start listening for client requests.
  server.Start();

  // Buffer for reading data
  Byte[] bytes = new Byte[1024];
  String data = null;

  // Enter the listening loop.
  while(true) {

    Console.Write("Waiting for a connection... ");

    // Perform a blocking call to accept requests.
    // You could also user server.AcceptSocket() here.
    TcpClient client = server.AcceptTcpClient(); 

    Console.WriteLine("Connected!");

    // Get a stream object for reading and writing
    data = null;
    NetworkStream stream = client.GetStream();
    int i;

    // Loop to receive all the data sent by the client.
    while((i = stream.Read(bytes, 0, bytes.Length))!=0) 
    {   
      // Translate data bytes to a ASCII string.
      data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
      Console.WriteLine("Received: {0}", data);

      // Process the data sent by the client.
      data = data.ToUpper();

      byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

      // Send back a response.
      stream.Write(msg, 0, msg.Length);
      Console.WriteLine("Sent: {0}", data);            
    }
}