I have simple server-clients programm:
public class Server extends Thread {
private ServerSocket server;
public Server(int port) {
try {
this.server = new ServerSocket(port);
System.out.println("New server initialized!");
this.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
Socket client = server.accept();
System.out.println(client.getInetAddress().getHostName()
+ " connected");
new ServerHandler(client);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Server handler must send message in stream:
public class ServerHandler extends Thread {
protected Socket client;
protected String userInput;
protected PrintWriter out;
protected BufferedReader console;
public ServerHandler(Socket client) {
this.client = client;
this.userInput = null;
this.start();
}
public void run() {
System.out.println("New Communication Thread Started");
System.out.println("Enter message:");
try {
this.out = new PrintWriter(client.getOutputStream(), true);
this.console = new BufferedReader(new InputStreamReader(System.in));
while ((this.userInput = console.readLine()) != null) {
this.out.println(userInput);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client side receives that message :
public class Client {
protected Socket client;
protected BufferedReader in;
public Client(String hostName, int ip) {
try {
this.client = new Socket(hostName, ip);
this.in = new BufferedReader(new InputStreamReader(
this.client.getInputStream()));
String buffer = null;
while ((buffer = in.readLine()) != null) {
System.out.println(buffer);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It works well with one client,but when I start new client problem with receiving message from server arises. What am I doing wrong?
synchronizeon your arraylist tho