Java Sockets writing/reading - java

So I want to read from socket , but it doesn't gives me anything , I am newbie to java networking so please help me , it doesn't gives me any errors but doesn't gives me any output from client socket too... here is a source code:
ServerSocket server = new ServerSocket(4444);
Socket client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputline = in.readLine();
while(inputline != null)
{
System.out.println("recieved "+inputline);
}
out.close();
in.close();
server.close();
client.close();

You call readLine() exactly once. If it's not null on the first iteration, you've got an infinite loop (because it will forever be non-null). Be sure to update it.

Related

java client side socket, if refused

This client side is talking to a single threaded server. Now, what i'm trying to do is, if client#2 tries to connect to the socket while client#1 is already actively connected to the server side, to do something else. so for example,
if(socket1.gotrefused){
system.out.println("It got refused");
My code below, (It's working perfectly for me, i just want to add the above one way or another..)
Socket socket1;
int portNumber = 4445;
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
String input = br.readLine();
while ((input = br.readLine()) != null) {
if(input.equals("Hi")){
pw.println("Hello");
}
else if(input.equals("Done")){
break;
}
br.close();
pw.close();
socket1.close();
}

Read multiple lines using BufferedReader (Socket)

I already read some threads here on stackoverflow, also some tutorials, but I don't find a solution to my problem.
I have Java client which connects to a server, then sends exactly one line to the server, and I get 2 or 3 lines as a response.
Here is my code:
public static void main(String[] args) {
String message;
String response;
try {
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket(hostname, port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
message = inFromUser.readLine();
outToServer.writeBytes(message + '\n');
// here my program "freezes"
while ((response = inFromServer.readLine()) != null) {
System.out.println("response: " + response);
}
clientSocket.close();
} catch (UnknownHostException e) {
System.out.println("Unknown Host");
} catch (IOException e) {
System.out.println("IO Exception");
}
}
My problem is, I can read every line of the response, but my program won't exit. The line clientSocket.close(); gets never called. What am I doing wrong?
Presumably your server isn't closing the connection - therefore the underlying stream for the reader isn't closed... at any point the server could send more information. readLine() only returns null when the stream has been closed, i.e. there will definitely not be any more data.
Now we don't know anything about the protocol here, but if the expected behaviour is that the client won't send any more information, and the server will close the connection, then the bug is in the server. If the protocol states that the server will keep the connection open, then the bug is in your client code and you need to work out how to detect the end of data (or send some sort of ack that will cause the server to close the connection, or whatever).

Java - Server and Client not interacting (Socket)

I'm currently working on a small chat-program. The 2 classes, I have a problem with are the classes containing the clientside and the serverside of a socket. I want them to interact, sending a string from the server to the client, but the string isn't received apparently. I also don't get an error. Can someone explain, why this happens or how to fix it?
Codesnippet from the client:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true) {
System.out.println("WAITING");
System.out.println(br.readLine());
}
} catch(Exception ex) { ex.printStackTrace(); }
Codesnippet from the server:
// Method of the code throws Exception
System.out.println("Waiting for someone to connect.");
Socket socket = serverSocket.accept();
System.out.println("Someone connected.");
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
while(true) {
System.out.println("WRITING");
pw.write("hi");
}
The output is currently:
server:
WRITING
WRITING
WRITING
WRITING
WRITING
...
client:
WAITING //only once
The client expects a complete line:
br.readLine()
and blocks until the line is complete.
But the server only sends "hi" repeatedly, without ever sending any EOL character:
pw.write("hi");
So the line never ends, and the client keeps blocking.
Use pw.println("hi");
The server buffer is not getting flushed. If you change pw.write(...) to pw.println(...) it should fix the issue - println(...) auto-flushes the buffer

Why does flush() effect println() on PrintWriter

I have the basic code for a server:
ServerSocket serverSocket = new ServerSocket(14000);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
String incoming;
while((incoming = in.readLine()) != null){
System.out.println("Client Says: " + incoming);
out.println("Client Says: " + incoming);
out.flush();
//if(incoming.equals("HELLO")) break;
}
clientSocket.close();
serverSocket.close();
I'm trying to further understand streams as they're giving me some serious headaches. From what I've read, println methods automatically flush for you, however this line is not delivered to the client unless the flush method is called afterwards? I'm just looking for a nice solid explanation of this?
To enable automatic flushing of the PrintWriter, the second argument of its constructor must be set to true.
I had this issue before, just:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
That will make the difference. If you do not autoflush you can get some errors or receive data as null, it happened to me some time ago. Best regards.

Sending a JSON object over TCP with Java

I'm trying to replace a Netcat command that I'm running in my terminal that will reset some data on a server. The netcat command looks like this:
echo '{"id":1, "method":"object.deleteAll", "params":["subscriber"]} ' | nc x.x.x.x 3994
I've been trying to implement it in Java since I would like to be able to call this command from an application I'm developing. I'm having issues with it though, the command is never executed on the server.
This is my java code:
try {
Socket socket = new Socket("x.x.x.x", 3994);
String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}";
DataInputStream is = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
os.write(string.getBytes());
os.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
The code also hangs on the while loop that should read the InputStream, I have no idea why. I've been using Wireshark to capture the packets and the data that is going out looks the same:
{"id":1,"method":"object.deleteAll","params":["subscriber"]}
Perhaps the rest of the packets are not shaped in the same way but I really can't understand why that would be. Perhaps I am writing the string in a faulty way to the OutputStream? I have no idea :(
Note that I posted a question similar to this yesterday when I didn't properly understand the problem:
Can't post JSON to server with HTTP Client in Java
EDIT:
These are the possible results I get from running the nc command, I would expect to get the same messages to the InputStream if the OutputStream sends correct data in a correct way:
Wrong arguments:
{"id":1,"error":{"code":-32602,"message":"Invalid entity type: subscribe"}}
Ok, successful:
{"id":1,"result":100}
Nothing to delete:
{"id":1,"result":0}
Wow, I really had no idea. I experimented with some different Writers like "buffered writer" and "print writer" and it seems the PrintWriter was the solution. Although I couldn't use the PrintWriter.write() nor the PrintWriter.print() methods. I had to use PrintWriter.println().
If someone has the answer to why other writers wouldn't work and explain how they would impact the data sent to the server I will gladly accept that as the solution.
try {
Socket socket = new Socket(InetAddress.getByName("x.x.x.x"), 3994);
String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}";
DataInputStream is = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
PrintWriter pw = new PrintWriter(os);
pw.println(string);
pw.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
I think the server is expecting newline at the end of the message. Try to use your original code with write() and add \n at the end to confirm this.

Categories

Resources