E
E
Eugene2016-06-09 18:23:17
Java
Eugene, 2016-06-09 18:23:17

Parallel processing of java client-server requests?

There is the simplest client-server, you can connect to the server and send messages from the client, the server returns the sent message back.
The catch is that it is serial, in other words, the socket is occupied by one client and the rest must wait until the end. There are no examples on the forums with handling multiple clients at the same time using the concurrent library.
Here is the client and server code:
Server:

public class Server {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int port = 6666; //мой некий порт
        try {
            ServerSocket ss = new ServerSocket(port); // создаем сокет сервера и привязываем его к вышеуказанному порту
            System.out.println("Ожидание клиента");

            Socket socket = ss.accept(); // заставляем сервер ждать подключений и выводим сообщение когда кто-то связался с сервером
            System.out.println("Клиент подключился");
            System.out.println();

            // Берем входной и выходной потоки сокета, теперь можем получать и отсылать данные клиенту. 
            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();

            // Конвертируем потоки в другой тип, чтоб легче обрабатывать текстовые сообщения.
            DataInputStream in = new DataInputStream(sin);
            DataOutputStream out = new DataOutputStream(sout) {
            };

            String line = null;
            while (true) {
                line = in.readUTF(); // ожидаем пока клиент пришлет строку текста.
                System.out.println("От клиента я получил следующую строку : " + line);
                System.out.println("Отправляю обратно...");
                out.writeUTF(line); // отсылаем клиенту обратно ту самую строку текста.
                out.flush(); // заставляем поток закончить передачу данных.
                System.out.println("Жду следующую строку...");
                System.out.println();
            }
        } catch (Exception x) {
            x.printStackTrace();
        }
    }
}

client:
public class Client {


    public static void main(String[] args) {
       int serverPort = 6666; // порт к серверу, которому хотим присоединиться
        String address = "127.0.0.1"; // это IP-адрес компьютера, где исполняется наша серверная программа. 
                                      // Здесь указан адрес того самого компьютера где будет исполняться и клиент.

        try {
            InetAddress ipAddress = InetAddress.getByName(address); // создаем объект который отображает вышеописанный IP-адрес.
            System.out.println("Если ли кто-то, подключенный по этому адресу " + address + " и порту " + serverPort + "?");
            Socket socket = new Socket(ipAddress, serverPort); // создаем сокет используя IP-адрес и порт сервера.
            System.out.println("Соединение установлено.");

            // Берем входной и выходной потоки сокета, теперь можем получать и отсылать данные клиентом. 
            InputStream sin = socket.getInputStream();
            OutputStream sout = socket.getOutputStream();

            // Конвертируем потоки в другой тип, чтоб легче обрабатывать текстовые сообщения.
            DataInputStream in = new DataInputStream(sin);
            DataOutputStream out = new DataOutputStream(sout);

            // Создаем поток для чтения с клавиатуры.
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            System.out.println("Введите что-нибудь, это будет отправлено на сервер и возвращено им.");
            System.out.println();

            while (true) {
                line = keyboard.readLine(); // ждем пока пользователь введет что-то и нажмет кнопку Enter.
                System.out.println("Отправляем строку на сервер...");
                out.writeUTF(line); // отсылаем введенную строку текста серверу.
                out.flush(); // заставляем поток закончить передачу данных.
                line = in.readUTF(); // ждем пока сервер отошлет строку текста.
                System.out.println("Сервер прислал ответ : " + line);
                System.out.println("Введите следующую строку...");
                System.out.println();
            }
        } catch (Exception x) {
            x.printStackTrace();
        }    }

}

How to make asynchronous processing of each client? And how to start several clients in general, in fact it's just 2 different projects in netbins, and when I start the server first, then the client - I start two projects, I can't start the client again. The button is grey.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question