疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 481, comments - 486, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

xsocket socket学习

Posted on 2009-11-17 14:53 疯狂 阅读(5919) 评论(3)  编辑  收藏 所属分类: java
     最近项目中想通过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

评论

# re: xsocket socket学习  回复  更多评论   

2011-04-19 17:53 by limingxing
您好,我拜读了您的xsocket做的聊天客户端与服务端。遇到一个疑惑:
public class XSocketClient {
public static void main(String[] args) throws IOException {
NonBlockingConnection bc = new NonBlockingConnection(host, port,new ClientDataHander());
}
}
我在main函数中实例化了bc,就是这样一个小程序,可是运行以后程序会马上关闭,我不得其解。
运行了您的代码,结果却又是非常正确的。我努力寻找我的代码与您的代码之间的区别,在于:我的main函数中实例化 NonBlockingConnection,而您的代码中 NonBlockingConnection的实例化不在main函数中。为什么这样的差别会造成现在的结果呢?如果我想自己的代码能顺利进行长连接该怎么办呢?
企盼您的解答。祝好~

# re: xsocket socket学习  回复  更多评论   

2011-04-25 10:07 by @joe
@limingxing
public static void main(String[] args) throws IOException {
NonBlockingConnection bc = new NonBlockingConnection(host, port,new ClientDataHander());
}
}
这明显不对啊,参数从哪来,姐姐。

# re: xsocket socket学习  回复  更多评论   

2012-02-10 09:44 by LSH744
请问服务端怎么发送消息给客户端啊

只有注册用户登录后才能发表评论。


网站导航: