简体   繁体   English

Java < - > C#Socket:无法接收消息

[英]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. 我需要在我自己编写的java服务器和C#客户端之间进行套接字通信,问题是C#客户端无法从我的java服务器接收任何消息,但是向我的java服务器发送消息是有效的。

my workflow: 我的工作流程

  1. Java: Create Server Java:创建服务器
  2. Java: Waiting for Client connection Java:等待客户端连接
  3. c#: Create Client c#:创建客户端
  4. c#: Build connection to the server c#:建立与服务器的连接
  5. c#: send a msg to the server c#:向服务器发送一个msg
  6. Java: msg received Java:收到消息
  7. java: send msg to c# client java:将msg发送到c#client
  8. c#: receiving msg from server <- this is the point where the client waits for a message but never get. c#:从服务器接收消息< - 这是客户端等待消息但从未得到的消息。

Java Server code: Java服务器代码:

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: 我的C#客户端代码:

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); 有人知道为什么它永远不会到达我的客户端代码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 谢谢

If your receiver is expecting lines , your sender has to send lines . 如果您的接收器正在等待线路 ,则您的发送方必须发送线路 Your sender does not send lines, so the receiver waits forever until it gets one. 您的发件人不会发送线路,因此接收器会一直等到它为止。

To avoid these kinds of problems in the future, you should always make a specification document that explains how your protocol works, ideally at the byte level. 为了避免将来出现这些问题,您应该始终制作一份规范文档,说明协议的工作原理,最好是在字节级别。 It should specify whether the protocol contains messages and if so, how the sender marks message boundaries and how the receiver identifies them. 它应指定协议是否包含消息,如果是,则指示发送方如何标记消息边界以及接收方如何识别它们。

Here, your receiver identifies message boundaries by looking for line endings. 在这里,您的接收器通过查找行结尾来识别消息边界。 But your sender doesn't mark message boundaries with line endings. 但是您的发件人不会使用行结尾标记邮件边界。 So the receiver waits forever. 所以接收器永远等待。

If you had a protocol specification, this would have been obvious. 如果您有协议规范,这将是显而易见的。 In the future, I strongly urge you to invest the time to specify every protocol you implement. 将来,我强烈建议您花时间指定您实施的每个协议。

You need to use println() which adds a new line instead of print(). 您需要使用println()添加一行而不是print()。 In Java, readLine waits for a new line and I would expect it to do the same in C#. 在Java中,readLine等待一个新行,我希望它在C#中也能这样做。 Also println will auto-flush, so you don't need to flush as well. println也会自动刷新,因此您也不需要刷新。

If you intend to use this connection mreo than once, you need to keep the BufferedReader and PrintWriter for the connection. 如果您打算使用此连接mreo多次,则需要保留BufferedReader和PrintWriter以进行连接。 (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. (所以我建议你在创建/接受套接字后创建这些套接字)为同一套接字创建多次这些可能容易出错并且容易混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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