简体   繁体   English

Java套接字(服务器)和C ++套接字(客户端)之间的网络通信

[英]Network Communication between a java socket (server) and a C++ socket (client)

I know this must be a pretty common problem, but I haven't been able to find a definitive answer on how to do it. 我知道这肯定是一个非常普遍的问题,但是我还没有找到关于如何做到的明确答案。

First, assume we have a java server that accepts queries such as (I've just put the relevant lines, and I've taken out the exception handling for clarity): 首先,假设我们有一个接受以下查询的Java服务器(例如,我已经放置了相关行,并且为了清楚起见,我进行了异常处理):

    ServerSocket socket = new ServerSocket(port);
    while (true) {
        ClientWorker w;
        w = new ClientWorker(socket.accept());
        Thread t = new Thread(w);
        t.start();
    }

and then in the ClientWorker 然后在ClientWorker中

    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
    DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());

    String query = inFromClient.readLine();
    // process query here
    String response = "testresponse";

    outToClient.writeBytes(response + "\n");

    outToClient.close();
    inFromClient.close();
    client.close();

Right now I can get a java client that works with this server: 现在,我可以获得与此服务器一起使用的Java客户端:

String query = "testquery";
Socket queryProcessorSocket = new Socket(queryIp,queryPort);
DataOutputStream queryProcessorDos = new DataOutputStream(queryProcessorSocket.getOutputStream());
BufferedReader queryProcessorReader = new BufferedReader(new InputStreamReader(queryProcessorSocket.getInputStream()));
queryProcessorDos.writeBytes(query + "\n");
String response = queryProcessorReader.readLine();

But how can I get a C++ client to do the same thing as the java client? 但是,如何让C ++客户端执行与Java客户端相同的操作? I've tried many things but nothing seems to work. 我尝试了很多事情,但似乎没有任何效果。 Ideally I wouldn't want to touch the java server, is that possible? 理想情况下,我不想接触Java服务器,这可能吗? If someone could point me to a good example or some sample code, that would be much appreciated. 如果有人可以给我指出一个好的例子或示例代码,那将不胜感激。 I searched through a lot of websites but to no avail. 我搜索了很多网站,但无济于事。

Here I put a simple code to connect to a server. 在这里,我放置了一个简单的代码来连接到服务器。 It may help you if this is your problem. 如果这是您的问题,可能会对您有所帮助。

void client(const char* server_address, short server_port)
{
     int     sockfd;
     struct sockaddr_in servaddr;

     sockfd = socket(AF_INET, SOCK_STREAM, 0);

     memset(&servaddr, 0x00, sizeof(servaddr));
     servaddr.sin_family = AF_INET;
     servaddr.sin_port = htons(server_port);
     inet_pton(AF_INET, server_address, &servaddr.sin_addr);

     connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

     //from this point you can start write to the server and wait for its respose

     std::string buffer = "testquery";
     writen(sockfd, buffer.c_str(), buffer.length());

     char *ReadBuffer[512];
     while(1)
     {
         memset(ReadBuffer, 0x00, sizeof(ReadBuffer));
         int n = readn(sockfd, ReadBuffer, sizeof(ReadBuffer));
         if(n <= 0)
         {
             //or you dont have anything to read, or you have a problem
             break;
         }
         //this function does the hard job of knowing what to do with all these data
         processBuffer(ReadBuffer, n);
     }

 close(sockfd);

 }

I'm using Posix standard and the code is very simplified but I think its a start point. 我使用的是Posix标准,代码非常简化,但我认为这是一个起点。

Regards. 问候。

How do you mean "it doesn't work" ? 您是什么意思“它不起作用”?

Without studying the code too carefully, my first concern is that you're converting a String (in chars, or byte-pairs) to bytes, and then sending these down the socket. 无需太仔细地研究代码,我首先要担心的是将字符串(以字符或字节对形式)转换为字节,然后将其发送到套接字。 Are you retrieving these in the same fashion on the C++ end ? 您是否在C ++端以相同的方式检索这些? ie using the same character encoding ? 即使用相同的字符编码?

As long as your're not using a language specific protocol (such as Java RMI) and using straight sockets (or some other language neutral protocol like web services) then it will work. 只要您不使用特定于语言的协议(例如Java RMI)并使用直插式套接字(或某些其他非语言中性协议,例如Web服务),它就会起作用。 You just have to make sure your client and server are speaking the same protocol (eg TCP/IP + your custom protocol on top). 您只需要确保客户端和服务器使用相同的协议即可(例如,TCP / IP +您的自定义协议位于最上方)。 If using straight sockets you're basically sending binary over the wire - so you need to make sure you're encoding/decoding the data the same on both sides. 如果使用直插座,则基本上是通过电线发送二进制文件-因此,您需要确保在两侧对数据进行相同的编码/解码。 Typically this is done with some sort of byte level protocol if you're rolling your own. 通常,如果您要自己滚动,则可以使用某种字节级别的协议来完成。 As an example Project Dark Star is a game server written in Java but has clients in Java, C/C++, Flash etc. It uses user defined a binary protocol for cross language communications. 例如, Project Dark Star是一个用Java编写的游戏服务器,但是具有Java,C / C ++,Flash等客户端。它使用用户定义的二进制协议进行跨语言通信。

I had the same problem prior. 我之前也遇到过同样的问题。 The client was C++ based and it has to connect to my Java-based server both running on Windows. 客户端基于C ++,并且必须连接到都在Windows上运行的基于Java的服务器。 I was stumped for the longest time why the Java server would drop connection upon client connection. 最长的时间让我感到困惑,为什么Java服务器会在客户端连接时断开连接。

Later I realised it because of the endian problems. 后来由于字节序问题,我意识到了这一点。 Java VM = big endian, C++ (on my hardware) was little endian. Java VM =大端,C ++(在我的硬件上)是小端。 Small problem but took a while to figure out for this amateur. 问题不大,但花了一些时间为这个业余爱好者弄清楚。

Yes you can have a C++ client (or a C client or a COBOL client or a perl client or a ruby client or a ... client) talk to a java server. 是的,您可以让C ++客户端(或C客户端或COBOL客户端,perl客户端,ruby客户端或...客户端)与Java服务器对话。 All you do is port the java code to the equivalent C++ code (or C code or COBOL code or perl code or ruby code or a ... code). 您要做的就是将Java代码移植到等效的C ++代码(或C代码或COBOL代码或perl代码或ruby代码或...代码)。 The server neither knows nor cares what language the client is written in. 服务器既不知道也不关心客户端使用哪种语言编写。

I would start with this reference Internet Sockets and then use the POSIX API Documentation. 我将从参考Internet套接字开始 ,然后使用POSIX API文档。

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

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