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

我知道这一定是一个非常普遍的问题,但我还没有找到关于如何做到这一点的明确答案.

首先,假设我们有一个接受查询的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服务器,这可能吗?如果有人可以给我一个很好的例子或一些示例代码,那将非常感激.我在很多网站上搜索过但无济于事.

最佳答案
在这里,我将一个简单的代码连接到服务器.如果这是你的问题,它可能会帮助你.

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标准,代码非常简单,但我认为它是一个起点.

问候.

转载注明原文:java套接字(服务器)和C套接字(客户端)之间的网络通信 - 代码日志