I'm trying to send a message to the server through a client, but I do not see the message on the Server. It shows it's connecting properly. I think the issue has something to do with this, in the Client class but I'm not too sure. Please let me know if anyone has a solution.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String send = reader.readLine();
out.println(send);
out.flush();
This is the client class:
package com.evolution.client;
import java.net.*;
import java.io.*;
public class Client {
private Socket client;
private PrintWriter out;
private BufferedReader in;
public static void main(String[] args) {
Client client = new Client();
client.startConnection("localhost", 325);
}
public void startConnection(String ip, int port) {
try {
client = new Socket(ip, port);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Connected");
out.println("Connection started from, " + client.getLocalAddress());
out.flush();
while (true) {
String recieve = in.readLine();
System.out.println(recieve);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String send = reader.readLine();
out.println(send);
out.flush();
}
} catch (Exception e) {
System.out.println(e);
}
}
public void stopConnection() {
try {
in.close();
out.close();
client.close();
}
catch (Exception e) {
}
}
}
This is the server class file:
package com.evolution.server;
import java.io.*;
import java.net.*;
public class Server {
private int port = 325;
private ServerSocket server;
private Socket client;
private PrintWriter out;
private BufferedReader in;
public static void main(String[] args) throws IOException {
Server server = new Server();
System.out.println("Start Up!");
server.start(server.port);
}
public void start(int port) throws IOException {
server = new ServerSocket(port);
try {
while (true) { //always runs unless break;
client = server.accept();
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out - send output
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.equalsIgnoreCase("shutdown"))
stop();
System.out.println(inputLine);
}
}
}
finally { //runs no matter what after try {}
server.close();
}
}
public void stop() {
try {
in.close();
out.close();
client.close();
server.close();
System.exit(0);
}
catch (Exception e) {
}
}
}
If you have any possible solutions please let me know.
The line String recieve = in.readLine(); on the client side will block (BufferedReader readLine() blocks). Since the server isn't sending more lines, your code is stuck there.
Removing this line allows you to send messages from the client to the server.