Reputation: 159
I made my one-on-one socket chat work between the server (myself) and the client (a friend in a different network). Now I'm trying to do the same but I'm trying to create multiple connections, placing them in an Executors.newFixedThreadPool(poolSize)
, where part of the code is taken from the ExecutorService
documentation.
The server works, and accepts connections, however, the problem occurs when I try to make a second connection and send messages to it. Although each client can send messages to the server, the server can only send messages to the first client.
Here is the full code:
public class MultipleServer implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
Scanner console;
public MultipleServer(int port, int poolSize, Scanner mainconsole)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
console = mainconsole;
}
public void run() {
try {
for(;;) {
pool.execute(new Handler(serverSocket.accept(), console));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
class Handler implements Runnable {
private Socket socket;
private Scanner console;
private String name = "undefined";
Handler(Socket socket, Scanner console)
{
this.socket = socket;
this.console = console;
}
public void run()
{
if (socket.isConnected())
{
System.out.println("connection from " + socket.getLocalAddress().getHostAddress());
Thread inputthread = new Thread(new Runnable()
{
@Override
public void run()
{
PrintWriter out;
try
{
out = new PrintWriter(socket.getOutputStream(), true);
out.println("Welcome to my server. Input your name");
out.flush();
String line;
while ((line = console.nextLine()) != null)
{
if (line.contains("/"))
{
if (line.equals("/q " + name))
{
out.println("Connection closing");
System.out.println("Connection to " + name + "closing");
out.close();
socket.close();
} else if (line.substring(0, name.length() + 3).equals("/m " + name))
{
out.println(line.substring(name.length() + 4));
out.flush();
}
} else
{
System.out.println("Incorrect command");
}
}
if (socket.isClosed())
{
out.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
});
Thread outputthread = new Thread(new Runnable()
{
int msgno = 0;
@Override
public void run()
{
BufferedReader in;
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!socket.isClosed())
{
while (!in.ready())
{
Thread.sleep(100);
}
String msg = in.readLine();
if (msgno == 0)
{
name = msg;
msgno++;
} else
{
System.out.println(name + ": " + msg);
}
synchronized (this)
{
this.wait(100);
}
}
if (socket.isClosed())
{
in.close();
}
} catch (IOException e)
{
e.printStackTrace();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
inputthread.start();
outputthread.start();
}
}
public static void main(String[] args) throws IOException
{
int connections = 10;
int port = 80;
Scanner scanner = new Scanner(System.in);
MultipleServer server = new MultipleServer(port, connections, scanner);
server.run();
}
}
More specifically, the exception thrown:
Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: end
at java.util.regex.Matcher.region(Unknown Source)
at java.util.Scanner.findPatternInBuffer(Unknown Source)
at java.util.Scanner.findWithinHorizon(Unknown Source)
at java.util.Scanner.nextLine(Unknown Source)
at Handler$1.run(MultipleServer.java:61)
at java.lang.Thread.run(Unknown Source)
Where the line in question is:
while((line=console.nextLine())!=null){
To clarify: this exception happens when the second user joins the server. When I type /m user1 message the first user gets the intended message, when I type /m user2 message, there are no errors, but the user2 doesn't get the message. Moreover, there is no "Incorrect command" message at the server console, meaning that the output to the second user isnt working
Upvotes: 0
Views: 586
Reputation: 4611
The main problem - you have too complicated threads management: several threads tries to read from console input simultaneously: user 1 reader thread and user 2 read thread.
You should introduce a single router thread, responsible for communication with administrator and manage all messages between spawned threads via shared concurrent structure(s).
For such tasks it would be better to use any existent frameworks, e.g. netty or nirvana messaging.
Upvotes: 1