Pedro
Pedro

Reputation: 4160

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

Upvotes: 0

Views: 1458

Answers (1)

Mike Haboustak
Mike Haboustak

Reputation: 2296

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.

Upvotes: 5

Related Questions