Nilesh Indalkar Nilesh Indalkar - 2 months ago 7
Java Question

Server is getting only null value java

In the following code the server simply get the text from the client and print it on console..

I.
but whenever client send some text the server receives only value as null,means on console its showing "null"

II. how can i use continuous data transmission means as client type one character the server will receives at same time and also printing at console..

Here is server:

try {
System.out.println("Server Has Started........ \nWaiting for client........");
serverSocket = new ServerSocket(SERVERPORT);
client = serverSocket.accept();
try {
while (!stop && running) {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String usercmnd = in.readLine();
System.out.println(usercmnd+"\n");
if (usercmnd != null) {
}break;
}
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}


here is client:

send.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
cs = new Socket(SERVERIP,PORT);
try{
out = new DataOutputStream(cs.getOutputStream());
out.writeBytes(text.getText().toString());
Toast.makeText(KeyboardActivity.this, "Success", Toast.LENGTH_LONG).show();
} catch (Exception ea) {
Toast.makeText(KeyboardActivity.this, ea.getMessage(), Toast.LENGTH_LONG).show();
}
}
catch (IOException e) {
Toast.makeText(KeyboardActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}

}

Answer

Please try this at the server side:

    String inputLine;        
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    String fullresponse = response.toString();

OR

You can simply do this at the client side:

out.writeUTF(text.getText().toString());//to write client data to server

and this at the server side:

String clientData= in.readUTF();//at server side to read data

rather than

out.writeBytes(text.getText().toString());