带有多个客户端的套接字服务器在java中 [英] Socket Server with multiple client in java

查看:145
本文介绍了带有多个客户端的套接字服务器在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个侦听多个客户端的套接字服务器。假设有6个客户端同时连接到服务器,并且每个客户端同时向服务器发送一些命令。如果这些客户端每1秒向服务器发送一条消息,我该如何处理来自服务器端的6个客户端的消息,以将其存储在表中并对每个客户端进行确认。

I have to create a socket server which will listen to multiple client. Suppose there are 6 clients connected to the server at the same time and each of the clients are sending some commands to server at the same time. If these clients sending the message to server for every 1 second how can I handle the those messages from the 6 clients on the server side to store it in the table and the acknowledgement to each client.

我如何处理来自客户端的这些输入。我是否必须创建6个线程来处理来自客户端的这些输入。

How can i handle these input from from the client. Whether I have to create 6 threads to handle these inputs from the client.

请给我一个解决此问题的想法。

Please give me a idea to approach this issue.

推荐答案

为每个客户端连接创建一个新线程,并不断对每个线程中的流执行阻塞读取以查找要处理的数据。

Create a new thread per client connection and continually do a blocking read on the streams in each thread to look for data to process.

class Server {

    ClientThread    threads[];
    int             size;
    ServerSocket    serverSocket;
    boolean         active;

    Server() throws Exception {
        /* initialize connection */
        active = true;
        listen();
    }

    void listen() throws Exception {
        while ( active ) {
            Socket clientSocket = serverSocket.accept();
            threads[ size++ ] = new ClientThread( clientSocket );
            threads[ size - 1 ].start();
        }
    }
}

class ClientThread extends Thread {

    OutputStream    out;
    InputStream     in;
    boolean         active;

    ClientThread( Socket clientSocket ) throws Exception {
        out = clientSocket.getOutputStream();
        in = clientSocket.getInputStream();
    }

    public void run() {
        active = true;
        while ( active ) {
            listen();
        }
    }

    private void listen() {
        try {
            int res = process( in.read() );
            out.write( res );
        } catch ( Exception e ) {}
    }

    private int process( int b ) {
        return -1;
    }
}

这篇关于带有多个客户端的套接字服务器在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆