简体   繁体   中英

Java TCP Client doesn't receive messages sent from C# Server

I'm writing a tcp server in c# and corresponding client in java. I'm testing the connection on localhost, and the client is able to connect to the server. However, when I'm sending messages, the client never receives them. Using the debugger I've verified that stream.Write(...) is executed. Any idea what the problem could be?

This is the c# server:

        TcpClient client = (TcpClient)cl;
        NetworkStream stream = client.GetStream();

        byte[] msg = new byte[512];
        int bytesRead; 

        while (running)
        {
            while (messages.getCount() > 0)
            {
                String msg = messages.Take();

                if (cmd != null)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(msg.ToCharArray());

                    try
                    {
                        stream.Write(bytes, 0, bytes.Length);
                        stream.Flush();
                    }
                    catch (Exception e)
                    {

                    }
                }
            }

            Thread.Sleep(1000); 
        }

And the Java client:

public void run() 
{
    try 
    {
        socket = new Socket(address, port);
        in = new BufferedReader( new InputStreamReader( socket.getInputStream() ));
        out = new PrintWriter(socket.getOutputStream());
        running = true;
    } 
    catch (Exception e){
        e.printStackTrace();
        running = false; 
    } 

    String data;
    while(running)
    {
        try 
        {
            data = in.readLine();

            if(data != null)
            {
                processData(data);
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();

            running = false; 
            break;
        }
    }

    try 
    {
        socket.close();
        socket = null;
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }

    running = false; 
}

You're using BufferedReader.readLine() . Are your message strings terminated by a CR, LF, or CR/LF?

readLine blocks until a line-terminating character is read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM