Search code examples
c#javasocketstcpmessage

Java <-> C# Socket: cant receive messages


I need a socket communication between my own written java server and C# client, the problem is that the C# client can't receive any messages from my java server, but sending messages to my java server works.

my workflow:

  1. Java: Create Server
  2. Java: Waiting for Client connection
  3. c#: Create Client
  4. c#: Build connection to the server
  5. c#: send a msg to the server
  6. Java: msg received
  7. java: send msg to c# client
  8. c#: receiving msg from server <- this is the point where the client waits for a message but never get.

Java Server code:

public class Communicator {

   private int m_port;
   private Socket m_socket;
   private ServerSocket m_serverSocket;

   public Communicator(int port) {
        this.m_port = port;
        initConnection();
    }

    private void initConnection() {

        try {
            System.out.println("Creating Server");
            m_serverSocket = new ServerSocket(m_port);
            System.out.println("Waiting for client connection");
            m_socket = m_serverSocket.accept();
            System.out.println("Connection made");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   public String sendMsg(JSONMessage msg) {
        try {

     //get msg
     BufferedReader bufferedReader = new BufferedReader(
           new InputStreamReader(m_socket.getInputStream()));
     System.out.println("Waiting for msg...");
       String answer = bufferedReader.readLine();
       System.out.println("Received: " + answer);

       //send msg
       PrintWriter writer = new PrintWriter(m_socket.getOutputStream(),true);
       writer.print(msg.getMsg());
       System.out.println("Sending: " + msg.getMsg());

       writer.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }

        return "";
    }

}

My C# client code:

class Communicator
    {
        private int m_port;
        private Thread mainThread;

        public Communicator(int port)
        {
            m_port = port;
            mainThread = new Thread(new ThreadStart(this.initConnection));
            mainThread.Start();
        }

        public void initConnection()
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_port);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                Console.WriteLine("Trying to build connection");
                server.Connect(ip);
                Console.WriteLine("Connection successful");

                NetworkStream ns = new NetworkStream(server);
                StreamReader sr = new StreamReader(ns);
                StreamWriter sw = new StreamWriter(ns);
                string data;

                string welcome = "Hello";
                Console.WriteLine("Sending: " + welcome);
                sw.WriteLine(welcome);
                sw.Flush();

                Console.WriteLine("Receiving...");
                data = sr.ReadLine();
                // --> NEVER REACHING THIS POINT <---
                Console.WriteLine("Received: " + data);                                         

            }
            catch (SocketException e)
            {
                Console.WriteLine("Connection failed.");
                return;
            }

        }
    }

Does somebody has any idea why it never reaches my client code Console.WriteLine("Received: " + data); ?

I already tried with waits on both sides. I'm not getting any exceptions or error so I don't have really an idea where my problem is.

Thanks


Solution

  • You need to use println() which adds a new line instead of print(). In Java, readLine waits for a new line and I would expect it to do the same in C#. Also println will auto-flush, so you don't need to flush as well.

    If you intend to use this connection mreo than once, you need to keep the BufferedReader and PrintWriter for the connection. (So I suggest you create these after the socket is created/accepted) Creating these multiple times for the same socket can be error prone and confusing.