c#java TCP连接丢失的消息

时间:2014-07-29 16:03:15

标签: java c# tcp client-server

这是Java监听器:

    while (true) {
        byte[] rvdMsgByte = null;
        String rvdMsgTxt = null;
        ServerSocket serverSocket = null;
        Socket workerSocket = null;
        DataInputStream socketInputStream;
        try {
            if (serverSocket == null) {
                serverSocket = new ServerSocket(5555);
                workerSocket = serverSocket.accept();
            }

            socketInputStream = new DataInputStream(
                    workerSocket.getInputStream());

            rvdMsgByte = new byte[socketInputStream.available()];

            for (int i = 0; i < rvdMsgByte.length; i++) {
                rvdMsgByte[i] = socketInputStream.readByte();
            }
            rvdMsgTxt = new String(rvdMsgByte);
            System.out.println(rvdMsgTxt);


        } catch (Exception ex) {
        }
        try {
            serverSocket.close();
            workerSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(tcpcsdinle.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

此代码为c#client:

        string mesaj ="blabla";
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect("192.168.1.114", 5555);
        int length = IPAddress.HostToNetworkOrder(mesaj.Length);
        byte[] buffer = new byte[mesaj.Length];
        buffer = System.Text.ASCIIEncoding.GetEncoding("iso-8859-9").GetBytes(mesaj);
        socket.Send(buffer,0,buffer.Length, SocketFlags.None);
        socket.Close();

第二个c#代码。我也尝试了这个:

    byte[] byteBuffer = System.Text.ASCIIEncoding.GetEncoding("iso-8859-9").GetBytes(mesaj);

    string mesaj = "blabla";
    int servPort = 5555;

    TcpClient client = null;
    NetworkStream netStream = null;

    try
    {
        client = new TcpClient("localhost", servPort);
        netStream = client.GetStream();
        netStream.Write(byteBuffer, 0, byteBuffer.Length);
        netStream.Flush();
        Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
    }
    catch (Exception ex) { 
    }

我的c#程序可以正确地从Java客户端接收消息。但是使用这些代码,前2条消息正常发送。在第二条消息之后,其中一些可以被服务器接收,其中一些不是。 Java为大多数没有正确接收的消息写了一个空白行。我无法找到问题所在。 java服务器正在一个线程中工作。一切看起来都像是在localhost上运行良好。请帮我。谢谢

0 个答案:

没有答案