Reputation: 6221
I got a Server with a ClientHandle which accepts requests if there are some and i'd like to send data from Java to it. (the C++ client does work without any issues)
I have read the other posts about this but they didnt help me in any way. Post1,Post2,Post3
bool ClientHandle::getData(std::shared_ptr<std::string> ptr)
{
int n;
ptr->clear();
char size[4];
n = recv(m_sock, size, sizeof(size), 0);
//check if retval passed
if (!checkRetValRecv(n))
return false;
//calc how much data
auto msgLen = atoi(size);
LOG_INFO << "recv a message with size: " << msgLen;
//create buffer for the data
auto buffer = new char[msgLen];
//read buffer
n = recv(m_sock, buffer, msgLen, 0);
//check retval if it passes
if (!checkRetValRecv(n))
return false;
ptr->append(buffer, msgLen);
LOG_INFO << "Message: " << *ptr;
delete[] buffer;
return true;
}
bool ClientHandle::checkRetValRecv(const int& n)
{
if (n == SOCKET_ERROR)
{
size_t err = WSAGetLastError();
if (err == WSAECONNRESET)
{
LOG_ERROR << "Failed to recv! Disconnecting from client: " << "Connection reset by peer.";
}
else
{
LOG_ERROR << "Disconnecting from client. WSAError: " << err;
}
m_connected = false;
return false;
}
if (n == 0)
{
LOG_INFO << "Client disconnected.";
m_connected = false;
return false;
}
return true;
}
Now i would like to write a Java client for this to send data but i cant even send the size of the incoming data.
public class JClient{
String m_host;
int m_port;
Socket m_sock;
OutputStreamWriter m_out;
BufferedReader m_in;
public JClient(String host, int port)
{
m_host = host;
m_port = port;
}
private void connect() throws IOException
{
m_sock = new Socket(m_host, m_port);
m_out = new OutputStreamWriter(m_sock.getOutputStream());
m_in = new BufferedReader(new InputStreamReader(m_sock.getInputStream()));
}
private void close() throws IOException
{
m_sock.close();
}
public void send(String json) throws IOException {
this.connect();
m_out.write(json.length());
m_out.flush();
m_out.write(json);
m_out.flush();
//wait for result
m_in.read();
this.close();
}
}
If i try to send Data like so:
JClient client = new JIMClient("localhost", 6060);
String toSend = "{\"hello\":\"someJson\"}";
try {
client.send(toSend);
} catch (IOException e) {
e.printStackTrace();
}
I do not receive anything usefull. recv a message with size: 0
, Client disconnected.
The send method does not work. I already tried other Streams and using a different encoding, which i guess is the reason for this. So the Question is how do i resolve this issue with the encoding here? I'd like to leave the C++ client as it is if possible or get it to some kind of standart.
Upvotes: 0
Views: 945
Reputation: 7008
Java code is only sending only a single character for the length but C++ expects a 4 byte string. You might try
m_out.write(String.format("%4d%s",json.length(),json));
m_out.flush();
Upvotes: 3