I'm creating a server app in C++ and client app in Java. I want to exchange 32 bit integer between them.
And I've got a trouble, because when I'm trying send something from Java's client, I get a random answer in C++ server (e.g. I've send '0' and one time I've got a one number, another time I've got different number. I've read about Little and Big Endian coding, but I think it is another issue, because sending '0' generate a huge value different from 0.
Java Client:
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws Exception{
Socket socket = new
Socket(InetAddress.getByName("127.0.0.1"),10000);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(0);
}
}
C++ Server:
#include <netinet/in.h>
#include <string>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include <iostream>
using namespace std;
int main(){
int port = 10000;
string ip_addr = "127.0.0.1";
int domain = AF_INET;
int type = SOCK_STREAM;
int protocol = 0;
int stopCondition = 0xFFFFFFFF;
int socketHandle;
struct sockaddr_in address;
int clientSocketHandle;
struct sockaddr_in clientAddress;
size_t clientAddressSize;
int buffer;
if((socketHandle=socket(domain,type,protocol))<0)
cout<<strerror(errno);
address.sin_family = domain;
inet_pton(domain,ip_addr.c_str(),&address.sin_addr);
address.sin_port=htons(port);
if((bind(socketHandle,(struct sockaddr *)&address,sizeof(address)))<0)
cout<<strerror(errno);
if (listen(socketHandle, 1) < 0)
cout << strerror(errno);
if ((clientSocketHandle = accept(socketHandle, (struct sockaddr *) &clientAddress, (socklen_t *) &clientAddressSize)) < 0)
cout << strerror(errno);
do {
if (recv(clientSocketHandle, &buffer, sizeof(int), 0) > 0)
cout<<buffer<<endl;
} while (buffer != stopCondition);
if(shutdown(clientSocketHandle,SHUT_RDWR)<0)
cout<<strerror(errno);
if(shutdown(socketHandle,SHUT_RDWR)<0)
cout<<strerror(errno);
return 0;
}
How should I implement my client in Java to work properly with my C++ server?
User contributions licensed under CC BY-SA 3.0