简体   繁体   中英

Java socket server cannot receive many data at the same time, how to make java socket server accept data at the same time?

my java socket server cannot accept more than one data at the same time in one client

Thread t1 = new Thread(() -> {
            ServerSocket ss = null;
            try {
                ss = new ServerSocket(9000);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                while(true) {
                    System.out.println("Waiting Transaction ..");
                    Socket clientSocket = ss.accept();
                    InetAddress inet = clientSocket.getInetAddress();
                    try{
                        while (clientSocket.getInputStream().available() == 0) {
                            Thread.sleep(100L);
                        }
                        byte[] data;
                        int bytes;
                        data = new byte[clientSocket.getInputStream().available()];
                        bytes = clientSocket.getInputStream().read(data,0,data.length);
                        String dataDB = new String(data, 0, bytes, "UTF-8");
                        System.out.println("received data\n time : "+ new Date() +"length data : " + dataDB.length());
                        System.out.println(dataDB);
                        String dataFrom = getFromServer(dataDB);
                        clientSocket.getOutputStream().write(dataFrom.getBytes("UTF-8"));
                    }catch (BindException be){
                        be.printStackTrace();
                    }catch(Exception e){
                        e.printStackTrace();
                    }finally {
                        clientSocket.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();

i try using thread but it not working, this code only accept the first data otherwise anoter data will be decline. how to server accept many data at the same time?

Let me tell you how I did it, while playing around with sockets, so I created a SocketServer class

public class Server {
    public static final Integer port = 9000;
    private final ServerSocket server;
    private final ExecutorService service = Executors.newFixedThreadPool(10);
    private final AtomicInteger idGenerator = new AtomicInteger(0);

    public Server() throws IOException {
        this.server = new ServerSocket(port);
    }

    public void start() {
        try {
            while (true) {
                Worker worker = new Worker(idGenerator.incrementAndGet(), server.accept());
                service.execute(worker);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now every time, a client joins, I create a worker thread and submit it to ExecutorService (Executor service has pool of threads and run the passed worker by allocating a thread to it, you can read about it).

The worker class looks like this

public class Worker implements Runnable {
    private final Socket client;
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public Worker(Integer id, Socket client) {
        this.id = id;   //Ignore it, it was for logging purpose, how many joined
        this.client = client;
    }

    @Override
    public void run() {
        listenClientMessages();

        closeConnection();
    }

    private void listenClientMessages() {
        final int MAX_INPUT = 1024;
        int read;
        try (InputStream is = client.getInputStream()) {
            byte[] buf = new byte[MAX_INPUT];
            while ((read = is.read(buf)) != -1) {
                String line = new String(buf, 0, read);
                log.info(line);

                if (line.equals("bye")) break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void closeConnection() {
        try{
            client.close();
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

So, you can see, I am reading bytes in while look

            byte[] buf = new byte[MAX_INPUT];
            while ((read = is.read(buf)) != -1) {
                String line = new String(buf, 0, read);
                log.info(line);

                if (line.equals("bye")) break;
            }

that's why when MAX_INPUT or less is processed, it would wait from client to send next input.

Let me know if it helps.

Edit: As commented by @user207421 in comments, closeConnection function is redundant as inputstream is closed with try-wit-resources block above in listenClientMessages function, so it is not needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM