P
P
parkito2016-04-30 17:50:32
Java
parkito, 2016-04-30 17:50:32

How to make a multi-threaded chat?

Hello. Please help me to solve the following problem.
I'm writing a chat. You need to make sure that multiple clients can connect to the server. Interaction with customers should occur in different threads.

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Server implements Runnable {

    private final PrintStream writerToScreen = System.out;
    final ServerSocket serverSocket = new ServerSocket(9001);
    static List<Thread> list = new ArrayList<Thread>();
        public Server() throws IOException {
    }


    public static void main(String[] args) throws IOException {
        Thread thread = new Thread(new Server());
        thread.start();
    }


    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(9001);
            Socket clientSocket = serverSocket.accept();
            PrintWriter writerToClient = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader readerFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            String line;
            while ((line = readerFromClient.readLine()) != null) {
                writerToScreen.println("recieved: " + line);
                writerToClient.println("I recieved your line [" + line + "]! sending back");
            }
            serverSocket.close();
            writerToClient.close();
            readerFromClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

However, I can't solve the problem that
ServerSocket serverSocket = new ServerSocket(9001);

must be the same for all Server objects . You can't make it static. Perhaps multithreading can be organized in a different way,

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-04-30
Protko @Fesor

you should have one main thread where you are waiting for connection. When you connect, you create a socket that you throw into a separate thread.
That is, your logic of work is not built correctly. When you receive a connection, you immediately start working with it, but you need to listen to new connections in a loop and start a thread for each.
I want to separately note that with an increase in the number of threads, performance will fall. Upon reaching the mark of a couple of hundred customers, for example. In this case it is better to switch to event loop/microthreads/coroutines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question