【问题标题】:Error in receiving data in C# client socket from java server socket从 Java 服务器套接字接收 C# 客户端套接字中的数据时出错
【发布时间】:2012-01-11 21:20:46
【问题描述】:

我正在使用 C# 客户端套接字和 Java 服务器套接字创建套接字连接。 当我从客户端套接字发送数据时,服务器套接字正在正确接收该数据。 但是当我试图从服务器套接字将数据发送回客户端套接字时,它在接收数据时会挂在客户端。

客户端代码(在 C#.net 中)

           clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            string hostName = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(hostName);
            System.Net.IPAddress[] ipAddresses = hostEntry.AddressList;
            System.Net.IPEndPoint remoteEP =
                new System.Net.IPEndPoint(ipAddresses[ipAddresses.Length - 1], port);
            clientSocket.Connect(remoteEP);
             string sendData = inputFilePath;
                    byte[] byteDataSend = System.Text.Encoding.ASCII.GetBytes(sendData);
                    clientSocket.Send(byteDataSend);

                    int receivedBufferSize = clientSocket.ReceiveBufferSize;
                    byte[] recivedData = new Byte[receivedBufferSize];
                    int receivedDataLength = clientSocket.Receive(recivedData);
                    string stringData = Encoding.ASCII.GetString(recivedData, 0, receivedDataLength);
                    textFilePath = stringData;
                    Console.Write(stringData);
                    clientSocket.Close();

服务器套接字代码(Java)

           Socket connection = server.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
            fileName = in.readLine();
            convertedFile =runConverter.convertDocumet(fileName);
            byte[] sendingData = convertedFile.getBytes("US-ASCII");
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            dos.write(sendingData, 0, sendingData.length);

告诉我什么是问题? 请帮忙...

【问题讨论】:

    标签: c# java serversocket


    【解决方案1】:

    这种 C# 代码的常见问题是同步接收。
    我总是建议进行异步读取,如this answer

    我不确定这是您问题的根源,但是如果您通过一些日志记录实现了异步接收,那么这很有可能会解决您的问题或使您的问题更加明显是。

    同步接收挂起确实表明 Java 没有将数据发送到 c# 正在侦听的同一个套接字,因此仔细检查这些端点也是一个好主意。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      相关资源
      最近更新 更多