I think it is really strange problem because I don't even know where to start when repairing it.
My problem is my client don't receive message send from server.
I know I provided very little amount of code but I think other code really does not matter in this problem. If you want me to provide more code comment and I will send it to you.
Server code
String s = "";
for(String a : Main.users.keySet()) {
s = s + a + " ";
}
System.out.println("Sendind message: " + "SERVER USERS " + s);
output.writeBytes("SERVER USERS " + s);
output.flush();
System.out.println("User message sent");
Main.users.keySet() returns Set of strings.
Server console
SERVER USERS test
User message sent
Client code
System.out.println("TEST 1");
while(true){
try {
reader = new BufferedReader(new InputStreamReader(input));
line = reader.readLine();
System.out.println("TEST 2");
Client console
I/System.out: TEST 1
I've edited the code to explain that better.
I've got Android application, which is client and Java server. I'm trying to send info from client to server, process that information and send the result back to client.
I'm using BufferedReader, InputStreamReader and DataOutputStream to send and receive messages.
So my Client.java has this code:
try {
//Sending message to server
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
outToServer.writeBytes(messageString + '\n');
outToServer.flush();
} catch (IOException e) {
System.err.print(e);
}
try {
System.out.println("This line is showing");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String res;
System.out.println("And this line is showing");
res=inFromServer.readLine();
System.out.println("But this never is");
System.out.println("Received: " + res); //This line is never printed in console
}catch (IOException e) {
System.out.println(e);
}
And my Server.java has this:
try{
System.out.println("Creating InputStream");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String message = inFromClient.readLine();
System.out.println("Received: " + message); //correct string received
} catch (Exception ex) {
System.out.println("Creating InputStream failed");
System.err.print(ex);
}
try{
String response = "Response from server"
DataOutputStream outToClient = new DataOutputStream(clientSocket.getOutputStream());
outToClient.writeBytes(response + '\n');
outToClient.flush();
System.out.println("Sent to client: " + response); //correct string is showing in console
} catch(Exception ex) {
System.out.print("Error! " + ex);
}
The thing is that my server gets the message correctly, as understandable string. It shows in console what it's sending to client and that also is understandable string.
But when I'm trying to get the message at client it does nothing.
inFromServer.readline() isn't throwing any exception to console and I don't know why it's not working.
I tried inFromServer.toString(), and then I received something, but it definitely wasn't the string sent from server. It was something like:
java.io.BufferedReader#b3d109a0
I don't know what I'm doing wrong. The sending/receiving function is called from login function, which is called from onPostExecute. I don't know how can do this from doInBackground.
BufferedReader.readLine() isn't working
Oh yes it is. Your error is in trying to convert the reader into a string, instead of using the line that was read.
Yo should remove the ready() test. It is pointless.
You should also use symmetrical streams. If you use Readersat one end you should use Writers at the other, such as BufferedWriter. Not DataOutputStream.
I suggest that this isn't the real code, and that there isn't a \n on the end of the sent message, which would explain readLine() blocking until the non-existent line terminator arrives, but you should redo this using BufferedWriter instead of DataOutputStream as mentioned above.
I'm programming an Server-Client Software, where the client connects to the server with an port request, the server opens a new port and sends back the new port number. Then the client communicates with an RSA shared AES key encryption and the port from the port request.
Well, it should be like that.
I had the program already running, only one client could connect to the server, and everything worked fine. But now I'm sending an "portreq" String to the server which should give a port reply. But when i check, if the incoming request is a "portreq" it gives me false. If i do same with .contains it gives me true. That's the first problem, and secondly:
When the server converts the port-Integer into an String and sends it, i can't transform it into a int again on the client-side:
java.lang.NumberFormatException: For input string: "6002������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at application.PowerPanelController.addDataToCpu(PowerPanelController.java:360)
at application.PowerPanelController.lambda$0(PowerPanelController.java:143)
at application.PowerPanelController$$Lambda$200/357277047.handle(Unknown Source)
at com.sun.scenario.animation.shared.TimelineClipCore.visitKeyFrame(TimelineClipCore.java:226)
at com.sun.scenario.animation.shared.TimelineClipCore.playTo(TimelineClipCore.java:167)
at javafx.animation.Timeline.impl_playTo(Timeline.java:176)
at javafx.animation.AnimationAccessorImpl.playTo(AnimationAccessorImpl.java:39)
at com.sun.scenario.animation.shared.InfiniteClipEnvelope.timePulse(InfiniteClipEnvelope.java:110)
at javafx.animation.Animation.impl_timePulse(Animation.java:1102)
at javafx.animation.Animation$1.lambda$timePulse$25(Animation.java:186)
at javafx.animation.Animation$1$$Lambda$186/1977464318.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.animation.Animation$1.timePulse(Animation.java:185)
at com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:344)
at com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:267)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:447)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:431)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$363(QuantumToolkit.java:298)
at com.sun.javafx.tk.quantum.QuantumToolkit$$Lambda$42/317723766.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Which i don't get because the String looks pretty much the same as i send it.
Here's my client side send and receive function
private String sendCommandNoAES(String command)
{
byte[] outData = new byte[1024];
byte[] inD = new byte[1024];
String message = "";
try
{
// create Socket
DatagramSocket socket = new DatagramSocket();
// build Packet
InetAddress serverIP = InetAddress.getByName(PowerPanelMain.ip);
outData = command.getBytes();
DatagramPacket out = new DatagramPacket(outData,outData.length, serverIP, PowerPanelMain.port); // send packet
socket.send(out);
logger.info("Sent an " + command + " Request non encrypted to " + PowerPanelMain.ip + ":" + PowerPanelMain.port);
// Receive answer
byte[] inData = new byte[1024];
DatagramPacket in = new DatagramPacket(inData,inData.length);
socket.receive(in);
inD = in.getData();
message = new String(inD,0,inD.length);
// Close Socket
socket.close();
logger.info("Go answer " + message + " from " + in.getAddress().toString() + ":" + in.getPort());
}
catch(Exception ee)
{
logger.error("Error while requesting data from server \n" + getStackTrace(ee));
return "offline";
}
return message;
}
This is where i send the portreq:
String portString = sendCommandNoAES("portreq");
int port = Integer.parseInt(portString);
Thats the server code:
byte[] inData = new byte[1024];
byte[] outData = new byte[1024];
String message;
DatagramSocket socket = null;
try
{
socket = new DatagramSocket(port);
System.out.println("Bound to " + port);
//JOptionPane.showMessageDialog(null, "Bound to " + String.valueOf(port), "Yeay", JOptionPane.OK_CANCEL_OPTION);
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(null, "Error occured! \n#002", "Error #002", JOptionPane.OK_CANCEL_OPTION);
}
...
DatagramPacket in = new DatagramPacket(inData,inData.length);
socket.receive(in);
InetAddress senderIP = in.getAddress();
int senderPort = in.getPort();
byte[] inc = in.getData();
message = new String(inc,0,inc.length);
System.out.println("Got " + message + " from " + senderIP + ":" + senderPort + " (byte array: " + inc.toString());
...
if(message.contains("portreq"))
{
System.out.println("Creatinfg answer");
outData = String.valueOf(portcount).getBytes();
DatagramPacket out = new DatagramPacket(outData,outData.length, senderIP, senderPort);
socket.send(out);
System.out.println("Sent " + String.valueOf(portcount));
UDPTraffic udpt = new UDPTraffic(portcount, this.mode);
udpt.start();
portcount++;
}
I'm really thankful to anyone who can solve/explain me why this is happening :D
inD = in.getData();
This merely reasserts the same value. Remove.
message = new String(inD,0,inD.length);
Wrong. You're ignoring the actual length of the received datagram. Change to:
message = new String(in.getData(), in.getOffset(), in.getLength());
You are sending a string of one size, yet on the other side you are reading the string of 1024 bytes - which you never sent. This will not do. You should either serialize string using serialize() method, or, if you want to send raw string bytes, send string length as a separate part of the message.
Im sending a message from an android device to the server app in c#... i have successfully sent message from mobile device and received or server but a message from server is not being received in its original form on mobile device...
C# code for sending message
if (message == "Share_Screen")
{
string msg = "Go to java Socket in Android";
byte[] bfr = Encoding.ASCII.GetBytes(msg);
MessageBox.Show("No of bytes to be send are "+bfr.Length);
socket.Send(bfr);
}
Java Code for Sending and receiving single message
try
{
Socket socket = new Socket(ip,5353);
byte[] receiverBuffer = new byte[28];
byte[] buffer = "Share_Screen".getBytes();
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(buffer,0,buffer.length);
//sending successfully this message to c# socket
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
dataInputStream.read(receiverBuffer);
String msg = receiverBuffer.toString();
dataOutputStream.close();
dataInputStream.close();
socket.close();
return msg;
//expected message is " Go to java Socket in Android "
//received message is " |b#52a5395c "
}
catch (IOException e)
{
return "error";
}
message im receiving in android device is like "|b#52a5395c"
Working on a HTTP client program using Netbeans.
So far I have gotten to here in my HttpClient class:
public class MyHttpClient {
MyHttpRequest request;
String host;
public MyHttpResponse execute(MyHttpRequest request) throws IOException {
//Creating the response object
MyHttpResponse response = new MyHttpResponse();
//Get web server host and port from request.
String host = request.getHost();
int port = request.getPort();
//Check 1: HOST AND PORT NAME CORRECT!
System.out.println("host: " + host + " port: " + String.valueOf(port));
//Get resource path on web server from requests.
String path = request.getPath();
//Check 2: ENSURE PATH IS CORRECT!
System.out.println("path: " + path);
//Open connection to the web server
Socket s = new Socket(host, port);
//Get Socket input stream and wrap it in Buffered Reader so it can be read line by line.
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
//Get Socket output stream and wrap it in a DataOutputStream so it can be written to line by line.
DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
//Get request method
String method = request.getMethod();
//Check 3: ENSURE REQUEST IS CORRECT GET/POST!
System.out.println("Method: " + method);
//GET REQUEST
if(method.equalsIgnoreCase("GET")){
//Send request to server
outToServer.writeChars("GET " + path + " HTTP/1.0");
//HTTP RESPONSE
System.out.println("WAITING FOR RESPONSE!");
String line = inFromServer.readLine();
System.out.println("Line: " + line);
}
//Returning the response
return response;
}
}
I have checked to ensure my request line is constructed correctly, as seen in the print statements throughout. However when I get to this line the program hangs:
System.out.println("WAITING FOR RESPONSE!");
String line = inFromServer.readLine();
I have no idea why... My server is localhost WAMP. It is up and running correctly. I have the file I am requesting stored on the localhost. I can access it through browser.
Any ideas what might be going wrong??
No CR or LF is one of your problems. You should be writing ASCII characters and may be a Host header.
outToServer.write(("GET " + path + " HTTP/1.0\r\n").getBytes("ASCII"));
outToServer.write("Host: myhost.com\r\n\r\n".getBytes("ASCII"));
outToServer.flush();