简体   繁体   English

在套接字客户端服务器上实现观察者模式

[英]Implements observer pattern on socket client server

Each client is registered as an observer once it connected to the server. 每个客户端连接到服务器后即注册为观察者。 When any client did changes, another clients would be notified. 当任何客户端进行更改时,将通知另一个客户端。

My problem is how could I keep the socket connected? 我的问题是如何保持套接字连接?

Can I store all connections like Socket[] and check their InputStream every second? 我可以存储所有类似Socket[]连接并每秒检查其InputStream吗?

I don't know if i got your problem right... But I'll give it a shot. 我不知道我是否解决您的问题...但是我会给您一个机会。

The Problem sems to be, that you have 1 ServerSocket and multiple sockets (one for each client) and now you want to get notified/informed about acitvity on these sockets. 问题是,您有1个ServerSocket和多个套接字(每个客户端一个),现在您想获得有关这些套接字的活动性的通知/通知。 so you plan on iterating through the list of sockets? 所以您打算遍历套接字列表?

The keyword is nonblocking I/O. 关键字是非阻塞I / O。 Search for the Keyword "selector" or "multiplexing". 搜索关键字“选择器”或“多路复用”。 I'll try to put up a simple example. 我将尝试举一个简单的例子。

I build a really minimal example. 我建立了一个非常小的例子。 But it is a start. 但这是一个开始。 This is the whole 这是整体

package server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;

public class Server {

public Server() throws IOException{
    Selector selector = SelectorProvider.provider().openSelector();
    ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(9000));
    ssc.configureBlocking(false);       
    ssc.register(selector, 
              SelectionKey.OP_ACCEPT);  


    while(true) {

      int readyChannels = selector.select();

      if(readyChannels == 0) continue;


      Set<SelectionKey> selectedKeys = selector.selectedKeys();

      Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

      while(keyIterator.hasNext()) {

        SelectionKey key = keyIterator.next();

        if(key.isAcceptable()) {
           System.out.println("acceptable");
           SocketChannel socketChan =  ((ServerSocketChannel)key.channel()).accept();
           socketChan.configureBlocking(false);
            socketChan.register(selector, SelectionKey.OP_READ);

        } else if (key.isConnectable()) {
            // a connection was established with a remote server.

        } else if (key.isReadable()) {
            System.out.println("Processing reading...");

            ByteBuffer buf = ByteBuffer.allocate(1024);
            int readedBytes = ((SocketChannel)key.channel()).read(buf);
            System.out.println("Readed: " + readedBytes);
            buf.flip();

            for(byte b : buf.array()) {
                System.out.print((char) b);
            }

        } else if (key.isWritable()) {
            // a channel is ready for writing
        }

        keyIterator.remove();
      }
    }
}

public static void main(String[] args) throws IOException {
    Server server = new Server();

}

}

I can run this, and connect via netcat on port 9000 to it, and send messages from there. 我可以运行它,并通过端口9000上的netcat连接到它,并从那里发送消息。 Just ONE Thread, with as many client connections as you like.... 只需一个线程,即可根据需要选择尽可能多的客户端连接。

I used this ressources/examples 我使用了此资源/示例

http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.html and http://docs.oracle.com/javase/7/docs/technotes/guides/io/example/index.html http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.htmlhttp://docs.oracle.com/javase/7/docs/technotes/guides/io/example/index。 html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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