Basic Java Echo Socket Communication Error - java

I have been looking through the multitudes of explanation of basic Java Socket use, and have constructed the following basic code for my own Server/Client echo pair. However, there is some hangup in the client code that I cannot find for the life of me. Perhaps someone else can spot it?
// Server Code:
try (ServerSocket serverSocket = new ServerSocket(22222);
Socket cSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(cSocket.getInputStream()))) {
System.out.println("Client connected: " + cSocket.getInetAddress().getHostAddress());
// console DOES print ^this line and correct IP when client is run.
String inLine;
while (true) {
inLine = in.readLine();
out.println(inLine);
if (inLine.equals("exit")) break;
}
// client code
try (Socket socket = new Socket("localhost", 22222);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));) {
String userIn;
while (true) {
System.out.print("Client> ");
userIn = consoleIn.readLine();
out.println(userIn); // code hangs here.
out.flush();
System.out.println("Server> " + in.readLine());
if (userIn.equals("exit")) break;
}

It isn't blocking there. It's blocking in the readLine() from the server. Try a flush() after the println() in the server.

Related

BufferedReader adding weird characters at the start of received message

Got a server running independently.
Server code for receiving a message is as follows:
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"utf-8"));
out = new PrintWriter(clientSocket.getOutputStream(), true);
objectOut = new ObjectOutputStream(clientSocket.getOutputStream());
Sending of the message is done by this:
Socket clientSocket = new Socket("IpAddress", portNumber);
ClientConnect newConnection = new ClientConnect(clientSocket,StockMarket.getStockMarket());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "utf-8"));
BufferedReader stdln = new BufferedReader(new InputStreamReader(System.in));
while ((userInput = stdln.readLine()) != null) {
out.println(userInput);
System.out.println("INPUTED:" + userInput);
System.out.println("ECHO: " + stdln.readLine());
}
The message is received by the server fine, however it has added chars at the start. For instance if I send "HELP", it will return:
��HELP
I've read a bit into the BufferedReader and the InputStreamReader, and I've seen a few times the function: Flush. However I don't understand how to implement it or where.
A nudge in the right direction would be great.

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();
}

IO stream in socket Java

First I apologize for my English. I'm trying to make a Client-Server connection in Java but I have a problem getting response from the server. When I close the server first, the client will receive a response from the server. If I close the client first, nothing happens.
Here is the code of the server:
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(),"8859_1"),1024);
DataOutputStream sendToClient= new DataOutputStream(socket.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(input.readLine());
if(sb.toString().equalsIgnoreCase("lamoyenne")) {
System.out.println(Esclave.moyenneTarif());
sendToClient.writeBytes(String.valueOf(Esclave.moyenneTarif()));
}
if(sb.toString().equalsIgnoreCase("nombrelieuentre100et200")) {
System.out.println(Esclave.nombreLieuEntre100et200());
sendToClient.writeBytes(String.valueOf(Esclave.nombreLieuEntre100et200()));
}
else {
System.out.println(Esclave.tarifParLieu(sb.toString()));
sendToClient.writeBytes(String.valueOf(Esclave.tarifParLieu(sb.toString())));
}
Here is the code for the client:
System.out.println("Type in: ");
this.connexion = new Socket(InetAddress.getLocalHost(),44000);
Writer output = new OutputStreamWriter(connexion.getOutputStream(), "8859_1");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
this.line = in.readLine();
//DataOutputStream sendToServer = new DataOutputStream(connexion.getOutputStream(),"8859_1");
//sendToServer.writeBytes(this.line+'\n');
output.write(this.line);
output.flush();
connexion.shutdownOutput();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
String temp = inFromServer.readLine();
System.out.println("FROM SERVER: "+ temp);

Socket Multithreading - Reading input stream pauses thread

I'm testing out sockets on my local machine. I'm trying to run both a socket and server in one program using threads. My server is an echo server so that it sends back whatever message it receives. My problem is that when I start both threads, on both the client and server, they 'freeze' when they reach the part where I read from the input stream. It works fine up to the part where the client sends the message. Afterwards, it simply stops as it appears that the client is waiting for a message and so is the server even if I already sent a message to the server via writing to the outputstream. What's wrong with the code?
Client.java
#Override
public void run() {
try {
Socket socket = new Socket("localhost", 22600);
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Client 1");
while (true) {
System.out.print("\nEnter text : ");
String inputText = input.readLine();
writer.write(inputText);
System.out.println("Client 2");
System.out.println("Client 3");
String s = br.readLine();
System.out.println("CLIENT RECEIVED : " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Server.java
#Override
public void run() {
try {
ServerSocket server = new ServerSocket(22600);
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
System.out.println("Server 1");
while (true) {
System.out.println("Server 2");
String s = br.readLine();
System.out.println("Server 3");
if (s == null) {
System.out.println("NULL SERVER SIDE ERROR");
break;
}
writer.write("ECHO : " + s);
System.out.println("SYSOUT ECHO " + s);
}
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You are writing a string that does not have an end-of-line at its end.
String inputText = input.readLine();
writer.write(inputText);
System.out.println("Client 2");
The inputText string does not include the end-of-line you typed. And you write it as-is to the server. However, the server tries to read a line:
String s = br.readLine();
System.out.println("Server 3");
So it will keep waiting until the client sends in a newline. But by now the client is waiting for an answer from the server, and now they are deadlocked.
So, you should add a writer.newLine() to the client, as well as the server's echo, which suffers from the same issue. It's also recommended, after each write, to use writer.flush(), on both server and client. Otherwise, it may wait until the buffer is full before actually writing, and the same deadlock will result.
The readLine method of BufferedReader requires a new line terminator to return a value (unless the end of Stream is reached), and then returns the line without this character. So the Client
Reads a line from the user into the variable inputText
Client writes inputText to the OutputStream
Server receives data, but waits until it receives a new line (which it does not).
If you wish to use new line as a delimiter for communication, append this to the end of the data sent
writer.write(inputText + "\n");

Java Sockets - Server hangs after client sends its response

Just trying to get a handle on sockets. The server and client are running in two different programs.
They seem to be connecting fine to each other but the client will not properly send its output to the server. The server just hangs. Here's the code:
Server:
private ServerSocket serverSocket;
private Socket client;
public void run() throws Exception {
serverSocket = new ServerSocket(20005);
while(currentState == Game.State.NORMAL) {
client = serverSocket.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String clientInput = in.readLine();
// Takes the client input string and does some simple game logic that returns a Gson object
Gson serverResponse = processInput(clientInput);
out.write(serverResponse.toString());
out.flush();
}
}
Client:
Socket clientSocket;
void run() throws Exception {
clientSocket = new Socket("192.168.0.24", 20005);
PrintWriter out;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Print the state of the game - returns false if state is win or lose.
while(printState()) {
out = new PrintWriter(clientSocket.getOutputStream(), true);
// This method just takes some input from the console
String clientInput = getInput();
out.write(clientInput);
out.flush();
String serverResponse = in.readLine();
updateState(serverResponse);
}
}
}
There is some underlying game logic that is happening but it's pretty minor and should be irrelevant. I imagine I am just misunderstanding something fundamental here.
Thanks all.
Make sure you send a newline character to match the in.readLine() statement in the Server.
out.write(clientInput + "\n");
The same applys when sending data from Server->Client.

Categories

Resources