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

发布于 2024-08-15 10:02:10 字数 1398 浏览 1 评论 0原文

我知道这肯定是一个非常常见的问题,但我一直无法找到如何做到这一点的明确答案。

首先,假设我们有一个接受以下查询的 java 服务器(我刚刚放置了相关行,并且为了清楚起见,我已经删除了异常处理):

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

然后在 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();

现在我可以获得一个 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();

但是我怎样才能让 C++ 客户端做与 java 客户端相同的事情呢?我尝试了很多方法,但似乎没有任何效果。理想情况下我不想接触java服务器,这可能吗?如果有人能给我指出一个很好的例子或一些示例代码,我将不胜感激。我搜索了很多网站但没有结果。

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):

    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

    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:

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? I've tried many things but nothing seems to work. Ideally I wouldn't want to touch the java server, is that possible? 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

虐人心 2024-08-22 10:02:10

这里我放置了一个简单的代码来连接到服务器。如果这是您的问题,它可能会帮助您。

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

 }

我正在使用 Posix 标准,代码非常简化,但我认为它是一个起点。

问候。

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.

Regards.

隔纱相望 2024-08-22 10:02:10

“这不起作用”是什么意思?

在没有仔细研究代码的情况下,我首先关心的是您将字符串(字符或字节对)转换为字节,然后将它们发送到套接字。您是否在 C++ 端以相同的方式检索这些内容?即使用相同的字符编码?

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 ? i.e. using the same character encoding ?

小女人ら 2024-08-22 10:02:10

只要您不使用特定于语言的协议(例如 Java RMI)并使用直接套接字(或其他一些与语言无关的协议,例如 Web 服务),那么它就可以工作。您只需确保您的客户端和服务器使用相同的协议(例如 TCP/IP + 顶部的自定义协议)。如果使用直套接字,您基本上是通过线路发送二进制文件 - 因此您需要确保两侧的数据编码/解码相同。如果您正在滚动自己的协议,通常这是通过某种字节级协议来完成的。例如 Project Dark Star 是一个用 Java 编写的游戏服务器,但有 Java、C/C++、Flash 等客户端它使用用户定义的二进制协议进行跨语言通信。

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. You just have to make sure your client and server are speaking the same protocol (e.g. TCP/IP + your custom protocol on top). 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.

—━☆沉默づ 2024-08-22 10:02:10

是的,您可以让 C++ 客户端(或 C 客户端、COBOL 客户端、perl 客户端、ruby 客户端或...客户端)与 java 服务器对话。您所做的就是将 java 代码移植到等效的 C++ 代码(或 C 代码或 COBOL 代码或 perl 代码或 ruby​​ 代码或...代码)。服务器既不知道也不关心客户端是用什么语言编写的。

我将从这个参考开始 Internet Sockets 然后使用 POSIX API 文档。

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. 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). 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.

风轻花落早 2024-08-22 10:02:10

我之前也遇到过同样的问题。客户端是基于 C++ 的,它必须连接到我的基于 Java 的服务器,两者都在 Windows 上运行。我很长时间都困惑为什么Java服务器会在客户端连接时断开连接。

后来因为字节序问题才意识到。 Java VM = 大端,C++(在我的硬件上)是小端。小问题,但这位业余爱好者花了一段时间才弄清楚。

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. I was stumped for the longest time why the Java server would drop connection upon client connection.

Later I realised it because of the endian problems. Java VM = big endian, C++ (on my hardware) was little endian. Small problem but took a while to figure out for this amateur.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文