客户端Hello world example,发送Hello World!到服务器上:
代码
//使用tcp进行连接   
SocketSession session = new SocketSession();   
//设置要连接的地址,这里是localhost 1234端口   
session.setSocketAddress(new InetSocketAddress("localhost",1234));   
//设置事件产生器   
session.setEventGenerator(new AutoCloseEventGenerator());   
//开始连接   
session.start(true);   
//发送Hello world!   
session.blockWrite(new ByteArrayMessage("Hello world!".getBytes()));   
//关闭连接   
session.close(true);  
服务器端Hello world example,接收客户端发过来的Hello World!,并打印出来:
代码
//建立一个普通的TCP服务   
SimpleServerSocketSession session = new SimpleServerSocketSession();   
//设置事件产生器,如果和上面一段程序一起运行,应该共享同一个事件产生器以提高效率   
session.setEventGenerator(new AutoCloseEventGenerator());   
//设置要监听的端口   
session.setListenPort(1234);   
//添加连接上SocketSession的事件监听器   
session.addSocketSessionListener(new SessionAdapter() {   
        //接收到消息,打印消息   
        public void messageReceived(Session session, Message message) {   
            System.out.println(message);   
        }   
});   
//开始服务   
session.start(true);  

解决方案 »

  1.   

    生成一个Session的实例。如果是进行普通TCP连接,可以创建一个SocketSession的实例;如果进行SSL TCP连接,可以创建一个SecureSocketSession的实例;如果进行UDP单播,可以创建DatagramSession实例;如果进行UDP多播,可以创建SimulatedMulticastSession实例等等。Session的继承关系图可以参见:http://cindy.sourceforge.net/Session.gif假设使用普通TCP连接,则: 代码
    SocketSession session = new SocketSession();  
      

  2.   

    设置Session关联的事件生成器。
    代码
    //设置事件生成器,用于给Session生成相应事件   
    session.setEventGenerator(new AutoCloseEventGenerator());    
    EventGenerator是一个事件生成器,用于为其关联的Session产生相应的事件。比如session收到数据,EventGenerator会给session一个接收到数据的event;如session关闭了,EventGenerator会给session一个关闭的event,不同的Session实现会根据不同的event做相应的操作。熟悉nio的用户可以阅读它的源码,它内部实现是用一个独立线程维持了一个内部Selector变量,在不停的进行内部循环,将产生的事件分发给其关联的session。所以一定要重用EventGenerator才能带来效率上的提高,不要每生成一个Session实例就关联一个新的EventGenerator,在大部分的情况下,所用的Session共用一个EventGenerator是一个比较好的做法。目前EventGenerator有两个实现,SimpleEventGenerator和AutoCloseEventGenerator,其区别在于SimpleEventGenerator需要手工关闭,而AutoCloseEventGenerator在其关联的所有Session都close后会自动关闭。(EventGenerator关闭后,其关联的Session都会关闭,模拟出的Session除外)EventGenerator/Event这两个接口的存在就是为了降低其与Session之间的耦合性。类似于消息机制,如果某个Session实现收到了一个其不知道的Event,就应该忽略该Event,只有收到了其可以识别的Event才去做相应的事情。