xsocket socket学习

     最近项目中想通过java来调用c来启动驱动程序 ,由于项目是部署在winCE上(内存30多m),初步定下使用socket,所以就看了下轻量级的开源xSocket ,感觉用起来挺简单,而且性能和效率不错。apace mina 也很强大但是功好多功能用不上也就没用。
      xSocket是一个轻量级的基于nio(since jdk1.5)的服务器框架用于开发高性能、可扩展、多线程的服务器。该框架封装了线程处理、异步读/写等方面。
    使用也很简单 :
server端: new Server(8090,new ServerDataHander()).start();
client端: new NonBlockingConnection("localhost", 8090,new ClientDataHander());
 其中ServerDataHander,ClientDataHander为自己定义类,都可以实现接口IConnectExceptionHandler, IConnectHandler, IDisconnectHandler等接口:通过重写回调函数来处理数据:操作相当方便。例如:
 
public   boolean  onData(INonBlockingConnection connection)
                
throws  IOException, BufferUnderflowException,
                ClosedChannelException, MaxReadSizeExceededException 
{
            
byte[] data = connection.readBytesByLength(connection.available());

            
//hander.
            return true;
        }


        @Override
        
public   boolean  onConnectException(INonBlockingConnection connection,
                IOException ioe) 
throws  IOException  {
            chatServer.area.append(
"error connect please try again\r\n");
            
return true;
        }


        @Override
        
public   boolean  onConnect(INonBlockingConnection connection)
                
throws  IOException, BufferUnderflowException,
                MaxReadSizeExceededException 
{
            chatServer.area.append(
"client["+connection.getRemoteAddress()+"] is connected\r\n");
            
return true;
        }


        @Override
        
public   boolean  onDisconnect(INonBlockingConnection connection)
                
throws  IOException  {
            chatServer.area.append(
"client["+connection.getRemotePort()+"] is disconnected\r\n");
            
return true;
        }

  下面是自己做的一个例子:
最终界面:
 server端:


客户端:


可运行代码下载(解压可用):
/Files/freeman1984/xsockettest.rar

你可能感兴趣的:(xsocket socket学习)