在看Mina源代码时发现其客户端Socket Connector的例子很少,耗费了我一些时间。相对传统IO的堵塞式,NIO 的优势和特色就在于非堵塞了。使用NIO的话,不管是服务器端还是客户端,都不用堵住了。这样就大大提高了服务处理的能力,也减少了等待的时间。当然,传统IO Socket编程通常都会使用一个专有线程监听连接请求,获悉新请求后产生其它线程来服务该连接。不管怎么样,这些服务都是同步操作。NIO就不一样了,什么都是通知的。打个比方,就像一个客人到商店预订商品,当商品齐全了,店长就可以将商品发送给客人,或者通知客人取货了。
由于采取了NIO,所以使用Mina时一定要有异步消息处理思想。这里提供一个简单的例子服务器端用传统IO 的ServerSocket,收到新请求后只是返回一个消息:
try {
Socket socket = this.serverSocket.accept();
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
if(dis.read(bytes) < 1024)
{
System.out.println(new String(bytes));
}
OutputStream os = socket.getOutputStream();
os.write(("This is server, your reservation number:["+i+"]").getBytes());
os.write(("\nAnything i can help?").getBytes());
os.flush();
os.close();
is.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
传统Socket客户端实现:
public void request(byte [] reequest, ResponseHandler handler)
{
if(!socket.isConnected()){
throw new IllegalStateException("Socket not connected to["+address+":"+port+"].");
}
OutputStream os = null;
InputStream is = null;
DataInputStream dis = null;
try {
os = this.socket.getOutputStream();
os.write(reequest);
os.flush();
is = this.socket.getInputStream();
dis = new DataInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] bytes = new byte[1024];
int len = 0;
while((len = dis.read(bytes)) != -1)
{
baos.write(bytes, 0, len);
}
handler.handleResponse(baos.toByteArray());
} catch (IOException e) {
}finally
{
try {
dis.close();
} catch (IOException e) {
}
try {
os.close();
} catch (IOException e) {
}
try {
this.socket.close();
} catch (IOException e) {
}
}
}
Mina的Socket Connector方式:
public void test1()
{
try {
final StringBuffer buf = new StringBuffer();
SocketConnector connector = new SocketConnector();
ConnectFuture future = connector.connect(new InetSocketAddress(
"localhost", 9999), new IoHandlerAdapter() {
public void sessionCreated(IoSession session) {
log.debug("Session Created");
buf.append("1");
}
public void sessionOpened(IoSession session) {
log.debug("Session Opened");
WriteFuture writeFuture = session.write(ByteBuffer.wrap("Hello".getBytes()));
writeFuture.join();
}
public void exceptionCaught(IoSession session, Throwable cause) {
log.debug("Exception,", cause);
buf.append("X");
}
@Override
public void messageReceived(IoSession session, Object message)
throws Exception {
if(message instanceof ByteBuffer)
{
ByteBuffer byteb = (ByteBuffer)message;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytearray = new byte[1024];
while(byteb.hasRemaining())
{
int len = Math.min(byteb.remaining(), 1024);
byteb.get(bytearray,0, len);
baos.write(bytearray, 0, len);
}
log.debug("Message from Server:" + new String(baos.toByteArray()));
}
}
@Override
public void messageSent(IoSession session, Object message)
throws Exception {
log.debug("Sent:" + message);
}
@Override
public void sessionClosed(IoSession session) throws Exception {
log.debug("Session closed.");
super.sessionClosed(session);
}
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
// TODO Auto-generated method stub
super.sessionIdle(session, status);
}
});
log.debug("connect future join begin.");
//等待连接准备
future.join();
log.debug("connect future join end.");
CloseFuture closeFuture = future.getSession().close();
log.debug("close future join begin.");
closeFuture.join();
log.debug("close future join end.");
}catch(Exception e)
{
e.printStackTrace();
}
}
分享到:
相关推荐
java客户端socket与mina服务端通信,保持长连接
运行客户端hello会弹出一个窗体,点击按钮模拟客户端主动发送。只是简单的例子很多没有处理,但是基本的数据连接没有问题
mina框架中socket使用,有服务端和客户端。这是比较完整的项目。希望能给后人点参考
socket的tcp/udp(多播) nio的tcp/udp mina 均有服务端/客服端
java mina 服务端,socket客服端传信息,客服端上传消息
Mina 服务端客户端示例程序
NULL 博文链接:https://joe-zhjiang.iteye.com/blog/801689
通过Mina与Socket实现通信,其包含客户端与服务端的实现代码
常见NIO开源框架(MINA、xSocket)学习 基于io包的阻塞式socket通信代码简单,在连接数很少的情况下是一个不错的选择。不过实际应用中一个socket服务器采用传统的阻塞式socket方式通信可能会是一场灾难,一路...
mina简单示例,Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务、虚拟机管道通信服务等),Mina 可以帮助我们快速...
NULL 博文链接:https://hfutfei.iteye.com/blog/1517487
minafileserver(Socket客户端+Mina服务端传文件)
mina客户端示例,包括一些封闭的帮助类,编码器,解码器,用起来也比较简单,本人是打成jar包供其他项目使用的.
mina测试框架 mina测试框架 mina测试框架
根据HPSocketCS.TcpPackServer server = new HPSocketCS.TcpPackServer();的封包规则进行mina拆包,解决断包,粘包问题。亲测,30ms一次数据,无丢包现象,20MB,300人使用网络,
Socket与mina交互,如果熟悉了解码协议,其他的就OK了。
该项目是采用mina框架做的客户端与服务端通信 mina框架相比socket通信有许多好处还是非常不错的 这个项目示例比较经典
apache mina 简单示例apache mina 简单示例apache mina 简单示例apache mina 简单示例apache mina 简单示例apache mina 简单示例
androidpn项目基础,socket和mina,详情见博客http://blog.csdn.net/specialshoot/article/details/50678374