多线程服务器异步java

时间:2014-06-13 08:31:24

标签: java multithreading jsp sockets

基本上我需要制作一个处理多个设备发送/接收信息的服务器。我必须能够向设备发送命令。现在设备数量约为40,但随着时间的推移将增加到400。设备将始终每隔40秒-60秒发送一次信息,该信息在设备上设置,因此可以变化,但也可能根据其他因素发送更多信息,例如对发送给它的命令的响应。所以我读过有我可以使用的java NIO,或者我现在所做的是为每个传入连接创建一个线程。发送不是一件永恒的事情,所以它需要根据我在jsp网站上的用户输入按需发生。所以这就是我被困住的地方。如何完成从连接所在程序外部发送命令。

这就是我目前所拥有的:

用于处理连接和创建线程的主服务器类。

    try (ServerSocket serverSocket = new ServerSocket(portNumber)) { 
    while (listening) {
      ServerThread r = new ServerThread(serverSocket.accept());
      Thread thread = new Thread(r);
      thread.setDaemon(true);
      System.out.println(thread.getId() + "thread");
      thread.start();
      thread.join();
         }
     } catch (IOException e) {
        System.err.println("Could not listen on port " + portNumber);
        System.exit(-1);
 } catch (InterruptedException e) {
   // TODO Auto-generated catch block
    e.printStackTrace();
 }

然后是ServerThread类:

    public class ServerThread implements Runnable{

private Socket socket = null;
public AtomicBoolean isStopped=new AtomicBoolean(false);

    public ServerThread(Socket socket) {
       this.socket = socket;
    }
    public void run() {
       while(!this.isStopped.get()){
        try (
            DataInputStream in = new DataInputStream(socket.getInputStream());
        ) {

         ReceiveThread r = new ReceiveThread(in);
         Thread thread = new Thread(r);
         thread.setDaemon(true);
         thread.start();
         thread.join();
         socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }
    }

    }

然后ReceiveThread处理读取/解码。

1 个答案:

答案 0 :(得分:0)

如果您需要确保收到数据,或者您可以使用NIO渠道来处理,那么根据需要,可以通过UDP更好地处理不频繁的通信,可能需要重新传输。 如果沟通不频繁,为每个客户创建Thread是浪费和毫无意义的。