Ending of "messages" exchanged between client and server sockets - java

Java server socket
In the following code:
https://docs.oracle.com/javase/tutorial/networking/sockets/examples/KnockKnockServer.java
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java KnockKnockServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
when the server sends its response to the client socket, it writes to the "PrintWriter" "out" using the "println()" method (line 63).
I have tried using the "print()" method instead.
In the "println()" case, the client socket receives the message properly.
In the "print()" case, the client socket doesn't receive anything.
Is this normal?
Is it required to send an EOF, a CR LF (in my case) (10 and 13 ASCII characters) at the end of the message?
Is it documented somewhere?
Winsock
In the following code:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737591%28v=vs.85%29.aspx
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
the "send()" method is used.
Does it implicitly send an EOF (a CR LF sequence for example) to the server socket at the end of the message passed as an argument?
Is it documented somewhere?
Is it part of the socket implementation?
Note that, I am not adding a EOF (CR LF for example) at the end of the message.
I'm ending the message with a trailing '\0' character.
When a "message" (an array of characters) is sent from a socket endpoint to another socket endpoint, does the message have to be ended with some kind of EOF? It appears to me now that it doesn't.

There is no general need to send an EOF sign in java socket communication, BUT
if your client uses InputStream.readLine() to read the servers answer, than this is normal, because
readLine() blocks until a line has been completely read (until \n \r or \r\n found) or the socket is closed by the server.
But in this example, the socket is not closed by the server, because the server is waiting for the clients answer and if the client is waiting for the end of line, you have a deadlock.

when the server sends its response to the client socket, it writes to the "PrintWriter" "out" using the "println()" method
PrintWriter is line buffered. See the Javadoc.
I have tried using the "print()" method instead.
If you don't write a line it won't flush. Call flush() afterwards. But you shouldn't use PrintWriter over a network, as it swallows exceptions you need to know about. Use BufferedWriter.
In the "println()" case, the client socket receives the message properly.
Because it's line-buffered, so there was an auto-flush.
In the "print()" case, the client socket doesn't receive anything.
Because it's line-buffered so there wasn't an auto-flush.
Is this normal?
Yes.
Is it required to send an EOF, a CR LF (in my case) (10 and 13 ASCII characters) at the end of the message?
No.
Is it documented somewhere?
Yes, in the Javadoc for PrintWriter.

Related

A socket with c server over java socket

My assignment requiers me to write an server in c but client in java. I need to send some integer to my client as instructions. They can connected smoothly but my java client cannot Receive the integer send from c server. there is only two possibilities: my c server did not send the Number out OR my client does not Receive the integer correctly. The c server is able to loop as I type in since the printf and scanf is executed while nothing happends on the client side.
I am stuck here, any help will be appreciate!
=========================================================================
UPDATE:
I correct the main class in java where the class name of the client into dotClient, and my client was able to conncected and read the inputs from the server.
I have try to send an 'int' directly in the server side, but When the client(java) use DataInputStream.ReadInt(), it returns a randomly big number as if the size of int in c and size of int in java is not matched.When I use a c client to do the same job, it works normal. So there is Hidden Problem for using dataInputStream directly with a c server, as I tried readShort() and ReadLong() as well.
As suggested, I use bufferReader.
And send string in server side, and perse it into int in client.
it works.
hère is my updated c code
#define PORT 55555
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024];
int returnSend = 0;
// Creating socket file descriptor
if (
(server_fd = socket(AF_INET, SOCK_STREAM, 0))
== 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
printf("%s\n", "Socket created!");
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET,
SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
printf("Socket attached!\n");
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd,
(struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("socket binded!\n");
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
printf("socket listened!\n");
if ((new_socket = accept(server_fd,
(struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}// Socket formulated !
do{
fgets(buffer, sizeof(buffer), stdin);
returnSend = write(new_socket , buffer , strlen(buffer));
printf("Sending: %sReturn returnSend: %d.\n", buffer,returnSend);
} while (1);
return 0;
}
hère is my updated java client
import java.net.*;
import java.io.*;
public class dotClient
{
// initialize socket and input output streams
private Socket echoSocket= null;
private BufferedReader input = null;
// constructor to put ip address and port
public dotClient(String address, int port)
{
// establish a connection
try
{
echoSocket = new Socket(address, port);
System.out.println("Connected");
input =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
}
catch(UnknownHostException u)
{
System.out.println("exception 1: "+u);
}
catch(IOException i)
{
System.out.println("exception 2: "+i);
}
int number = 0;
String line = "";
// keep reading until read neagaive integer
try
{
while ((line = input.readLine()) != null)
{
number = Integer.parseInt(line);
System.out.println("String is :"+line);
System.out.println("number is :"+number);
}
}
catch(IOException i)
{
System.out.println("Exception 3: "+i);
}
// close the connection
try
{
input.close();
out.close();
echoSocket.close();
System.out.println("Connection closed!");
}
catch(IOException i)
{
System.out.println("Exception 4: "+i);
}
}
public static void main(String args[])
{
dotClient client = new dotClient("192.168.0.3", 55555);
}
}
In your main method you are creating a Client instance but your class is called dotClient. You might want to ensure you are creating an instance of your class dotClient. Otherwise I agree with the previous comments and would suggest BufferedReader and BufferedWriter/PrintWriter for the IO.
Do any of your try blocks catch an exception on the client? Check the return value of send(new_socket , &number , size(number) , 0 ); on the server to make sure the data was actually sent for more info checkout http://man7.org/linux/man-pages/man2/send.2.html.

Cannot get response from Java server to C++ client

My C++ client shown below
#include "mbed.h"
#include <TCPSocket.h>
#include <EthInterface.h>
#include "EthernetInterface.h"
#include "string.h"
#include "ESP8266Interface.h"
ESP8266Interface wifi(D1, D0);
void ClearBuffer();
char rbuffer[300];
int rcount;
int main() {
printf("Main\n\r");
printf("Connecting...\n\r");
int ret = wifi.connect("ssid","password", NSAPI_SECURITY_WPA_WPA2);
if (ret != 0) {
printf("\r\n*** WiFi Connection error ***\r\n");
return -1;
}
printf("IP Address is %s\r\n", wifi.get_ip_address());
//create socket
TCPSocket sock;
sock.open(&wifi);
int ret2 = sock.connect("address", port);//ip of google cloud VM
if(ret2 != 0)
{
printf("*** Socket connection error ***\r\n");
return -1;
}
sock.set_blocking(false);
//sending to java server
char sbuffer[] = "Hello from client\r\n\r\n";
int scount = sock.send(sbuffer, sizeof sbuffer);
printf("sent %d [%.*s]\r\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
//recieve from java server
rcount = sock.recv(rbuffer, sizeof rbuffer);
printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
printf("Done\r\n");
// sock.close();
wifi.disconnect();
}
And the Java server
System.out.println("Just connected to " + server.getRemoteSocketAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
Waiting for client on port 8082...
Hello from client
But when i try and send something back to C++ client like this:
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
String s = "Hello from server\0";
out.println(s);
out.flush();
C++ client code to receive:
rcount = sock.recv(rbuffer, sizeof rbuffer);
printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rebuffed);
My output is:
sent 22 [Hello from client]
recv -3001 []
Can anybody help me figure out why the string I send back to the c client is not working?
Thank you.
strstr(), printf("%s...") etc. operate on NUL-terminated char arrays. Calling them on arrays that are not securely NUL-terminated is undefined behaviour, eg:
rcount = sock.recv(rbuffer, sizeof rbuffer);
printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rebuffed);
try:
rcount = sock.recv(rbuffer, (sizeof rbuffer)-1);
if(rcount>0){
rbuffer[rcount]='\0';
printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rebuffer);
}
else
if (rcount=0) (printf("Socket closed")
else
printf("Error on socket"); // get perror, errno, getLastError or whatever..

C server and java client

I created a C server and a java client. I was sending a command like ls through the client and server should execute it. However read in c server is still waiting for input. how to solve this problem.
Java client
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
class HelloWorld
{
public static void main(String... abc) {
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter ip and port : ");
String ip ;
String p;
String ss;
int port;
ip = br.readLine();
p = br.readLine();
port = Integer.parseInt(p);
Socket s = new Socket(ip,port);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
Scanner in = new Scanner(System.in);
ss = in.nextLine();
pw.print(s);
pw.flush();
pw.close();
}
catch(Exception e){
System.out.println("ERROR!!!");}
}
}
here is the c server.
#include"Headers.h"
void comm(char * s_port)
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[MAXBUFFER];
char newbuffer[MAXBUFFER];
char var[MAXBUFFER] = " > file.txt";
int n;
struct sockaddr_in serv_addr, cli_addr;
FILE *fp = NULL;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(s_port);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
if (newsockfd < 0)
error("ERROR on accept");
while (1)
{
bzero(buffer,1024);
n = read(newsockfd,buffer,1024);
if (strcmp(buffer , "exit\n") == 0)
break;
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
strcpy(newbuffer,"");
if (buffer[strlen(buffer) - 1] == '\n')
buffer[strlen(buffer) - 1] = '\0';
strcat(newbuffer, buffer);
strcat(newbuffer, var);
printf("%s",newbuffer);
system(newbuffer);
break;
if (n < 0) error("writing to socket");
}
close(newsockfd);
close(sockfd);
}
n = read(newsockfd,buffer,1024);
if (strcmp(buffer , "exit\n") == 0)
break;
You forgot to implement a protocol. You can't just read an arbitrary bunch of bytes from the connection and then treat it as a message. TCP has no conception of a message. If you want to send and receive messages, you have to define what you mean by a "message" and write code to send and receive that implements that definition.
There are probably other problems with your code, but this defect is so severe and so fundamental, you really need to fix it first.
If your definition of a message is "a sequence of ASCII characters not including a zero byte or a newline terminated by a newline", then you need to write code to receive such a sequence. You can't just call read and expect it to find the message boundaries since it has no idea that you use newline as a message boundary.
The main problem with your code is the way you handle strings in C.
Your server seems to assume that you are sending UTF-8 encoded strings over the network but strings in Java are encoded in UTF-16 by default. You will also need a way to ensure that each message buffer only contains valid Unicode characters. Each character in a Unicode string can use multiple bytes and you might get partial sent characters on the server side.
You have a small typo in the java program:
pw.print(s);
s is the socket, so you are sending s.toString().
I think you mean:
pw.print(ss);
Also, you need to decide on a message protocol, just as #DavidSchwartz points out.
Some useful links:
Protocol types
Understanding and designing socket message protocols

Socket Java to C++ - Messages are always 8192 characters long

I am implementing a TCP socket connection from a java to a C++ programm. Currently it's one way but should become two-way someday. My messages are pretty long (~100.000 characters). Somehow my application only sends 8192 characters/bytes at once. How can that be? Is there any tool that can help debugging? Both, client and server, run on a local windows machine. I am not familar with network programming, so any help is appreciated! Thanks alot in advance!
Here is my code so far:
JAVA:
make a connection:
try {
serverSocket = new ServerSocket(socketPort);
System.out.println("waiting for client ...");
while (true) {
clientSocket = serverSocket.accept();
System.out.println("client connected.");
if (clientSocket!=null) break;
}
}
catch (IOException e) {
System.out.println(e);
}
send stuff:
OutputStream out = clientSocket.getOutputStream();
BufferedReader in = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
//send the new data to client
PrintWriter pw = new PrintWriter(out, true);
String outString = "VERY LONG TEXT ENDING WITH SPECIAL LETTER LIKE $";
pw.println(outString);
C++:
make a connection
bool connectToHost(int PortNo, char* IPAddress)
{
//Start up Winsock…
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
//Did something happen?
if (error)
return false;
//Did we get the right Winsock version?
if (wsadata.wVersion != 0x0202)
{
WSACleanup(); //Clean up Winsock
return false;
}
//Fill out the information needed to initialize a socket…
SOCKADDR_IN target; //Socket address information
target.sin_family = AF_INET; // address family Internet
target.sin_port = htons (PortNo); //Port to connect on
target.sin_addr.s_addr = inet_addr (IPAddress); //Target IP
mSocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); //Create socket
if (mSocket == INVALID_SOCKET)
{
return false; //Couldn't create the socket
}
//Try connecting...
if (connect(mSocket, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
{
return false; //Couldn't connect
}
else
return true; //Success
}
receive stuff:
if (connectToHost(3141, "127.0.0.1"))
{
int iResult;
char recvbuf[DEFAULT_BUFLEN]; // DEFAULT_BUFLEN = 1000000
// Receive until the peer closes the connection
do {
iResult = recv(mSocket, recvbuf, DEFAULT_BUFLEN, 0); // DEFAULT_BUFLEN = 1000000
if ( iResult > 0 )
{
std::cout<<"recvbuf: "<< recvbuf[strlen(recvbuf)-1]<<""<< std::endl; //not the last character that I sent, but supposed to be
std::cout<<"recvbuf size: "<< iResult <<""<< std::endl; //fist are 8192 and then add up until sent size
}
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
} else
{
printf("connect failed\n");
}
TCP sockets work on a byte stream concept. The TCP socket ensures your data arrives without error and in order as a byte stream. The sender adds bytes to the TCP byte stream, and the socket takes care of sending them to the destination. The socket does not separate your logical messages; it is your responsibility to insert separators for any logical messages that are embedded in the byte stream. The TCP socket does not necessarily send a packet on the socket every time you write bytes to the socket. This is to increase the efficiency, as measured by the number of data bytes versus the total bytes sent (data + overhead). You can read about Nagle's algorithm for TCP.
When reading from a socket, you are again consuming the byte stream. The number of times you need to call receive may not match the number of times send was called. But you know the correct bytes will be delivered in order, and the number of these bytes will be the same as those sent.
The size 8192 is probably the buffer size that triggers sending a packet.
If you send only 1 byte, then flush the socket, you should see only the one byte on the receiving end. You can also disable Nagle's algorithm by setting TCP_NODELAY in the java socket options.
You can't receive more at a time than was in the socket receive buffer. Raise the socket receive buffer size from 8192, with setsockopt(), and do the same at the sending end for the socket send buffer.

Sending string from Java (PC) to C (Raspberry Pi) via Socket

I have two apps, one written in Java that sends string, it looks like this:
import java.io.*;
import java.net.*;
public class Gniazdo{
public static void main(String[] args) throws IOException {
DataOutputStream dataOutputStream = null;
Socket socket = null;
String mes = "Test message";
try {
socket = new Socket("192.168.1.116", 4014);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeChars(mes);
} catch (UnknownHostException e) {
System.err.print(e);
} finally {
if(socket != null) {
socket.close();
}
if(dataOutputStream != null) {
dataOutputStream.close();
}
}
}
}
and second one is written in C and runs on Raspberry Pi, that should receive string :
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <string.h>
int main(void) {
unsigned int port;
char bufor[1024];
int gniazdo, gniazdo2;
struct sockaddr_in adr, nadawca;
socklen_t dl;
printf("Enter port to listen : ");
scanf("%u", &port);
gniazdo = socket(AF_INET, SOCK_STREAM, 0);
adr.sin_family = AF_INET;
adr.sin_port = htons(port);
adr.sin_addr.s_addr = INADDR_ANY;
if (bind(gniazdo, (struct sockaddr*) &adr,
sizeof(adr)) < 0) {
printf("Bind failed.\n");
return 1;
}
if (listen(gniazdo, 10) < 0) {
printf("Listen failed.\n");
return 1;
}
printf("Waiting for connection ...\n");
while (gniazdo2 = accept(gniazdo,
(struct sockaddr*) &nadawca,
&dl)
)
{
// memset(bufor, 0, 1024);
recv(gniazdo2, bufor, 1024, 0);
printf("message from %s: %s\n", inet_ntoa(nadawca.sin_addr), bufor);
close(gniazdo2);
}
close(gniazdo);
}
and my output is:
Enter port to listen : 4014
Waiting for connection ...
message from 192.168.1.103:
message from 192.168.1.103:
message from 192.168.1.103:
message from 192.168.1.103:
Please could anyone tell me whats wrong?
Why i don't receive the message?
I even checked packets outgoing from my computer with Wireshark and they contains my message, but still don't know where I made mistake
1) Try calling writeBytes(String s) on the DataOutputStream.
2) Try calling flush on the DataOutputStream
(even though close should be calling flush anyway).
3) Try using PrintWriter to send the String
See
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#PrintWriter%28java.io.OutputStream,%20boolean%29
and this method in particular
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#write%28java.lang.String%29
4) Also, I think you should swap these two
if(socket != null) {
socket.close();
}
if(dataOutputStream != null) {
dataOutputStream.close();
}
printf is looking at 'bufor' as a char (8-bit), but java will write 16-bit UTF-16 characters. The first byte of the first character is 0. printf sees the 0 and thinks it's the end of the string. Try formatting the string to UTF-8 when you write it to the socket or reading it and printing it as a wchar.

Categories

Resources