I'm trying to implement client to client chat which goes through the server.
But it is giving me Concurrent execution exception.
Any advice will be very appreciated.
The source code I've managed to write:
public class Server {
int port;
ServerSocket server=null;
Socket socket=null;
ExecutorService exec = null;
ArrayList clients = new ArrayList();
DataOutputStream dos=null;
public static void main(String[] args) throws IOException {
Server serverobj=new Server(2000);
serverobj.startServer();
}
Server(int port){
this.port=port;
exec = Executors.newFixedThreadPool(2);
}
public void startServer() throws IOException {
server=new ServerSocket(2000);
System.out.println("Server running");
while(true){
socket=server.accept();
dos = new DataOutputStream(socket.getOutputStream());
clients.add(dos);
ServerThread runnable= new ServerThread(socket,clients,this);
exec.execute(runnable);
}
}
private static class ServerThread implements Runnable {
Server server=null;
Socket socket=null;
BufferedReader brin;
Iterator it=null;
Scanner sc=new Scanner(System.in);
String str;
ServerThread(Socket socket, ArrayList clients ,Server server ) throws IOException {
this.socket=socket;
this.server=server;
System.out.println("Connection successful with "+socket);
brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
it = clients.iterator();
}
@Override
public void run() {
try
{
while ((str = brin.readLine()) != null)
{
{
try
{
DataOutputStream oss=it.next();
oss.writeChars(str);
}
catch(Exception ex){
System.out.println("Error 1 "+ex);
}
}
}
brin.close();
socket.close();
}
catch(IOException ex){
System.out.println("Error 2 "+ex);
}
}
}
}
public class Client1 {
public static void main(String args[]) throws IOException{
String str;
Socket socket=new Socket("127.0.0.1",2000);
BufferedReader brin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream prout=new PrintStream(socket.getOutputStream());
BufferedReader bread=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Send to Server:");
str=bread.readLine();
prout.println(str);
while(true){
str=brin.readLine();
System.out.print("Server:"+str+"\n");
}
}
}
Please help me fix the code...
I was trying to fix it for hours but to no avail.
You are iterating the clients list in one thread (while (it.hasNext())
) while another one is adding items to it (clients.add(dos);
).
You could avoid the exception for example by passing a copy of the list to teach new thread:
ServerThread runnable= new ServerThread(socket,new Arraylist<>(clients),this);