minaTcp实例

2 篇文章 0 订阅
tcp连接协议实例。
完整代码请在附件中下载。

直接先启动服务端,再启动客户端即可

//服务端打印信息为:
[10:49:57] main INFO  [] [] [com.tcp.server.TcpServer] - Starting Server.... and then Listening on:8880
[10:49:57] main INFO [] [] [com.tcp.server.TcpServer] - Server listening on 8880
[10:50:58] NioProcessor-2 INFO [] [] [com.tcp.server.TcpServer] - 服务端:sessionCreated...2015-09-30 10:50:58
[10:50:58] pool-3-thread-1 INFO [] [] [com.tcp.server.TcpServer] - 服务端:sessionOpened...2015-09-30 10:50:58
服务端:messageReceived...sessionCreated客户端--Wed Sep 30 10:50:58 CST 2015
[10:50:58] pool-3-thread-1 INFO [] [] [com.tcp.server.TcpServer] - 服务端:messageSent...2015-09-30 10:50:58
[10:51:00] pool-3-thread-2 INFO [] [] [com.tcp.server.TcpServer] - 服务端:messageSent...2015-09-30 10:51:00
[10:51:01] pool-3-thread-1 INFO [] [] [com.tcp.server.TcpServer] - 服务端:sessionClosed...2015-09-30 10:51:01

//客户端打印信息为:
Starting client.... and then connect to-- 127.0.0.1:8880
客户端:sessionCreated...
客户端:sessionOpened...
客户端:messageSent...
客户端:Client ---messageReceived...
客户端:来至服务器的消息:{"name":"aobama"} name:aobama
客户端:Client ---messageReceived...
客户端:exceptionCaught...



服务端Server代码
package com.tcp.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.firewall.BlacklistFilter;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.tcp.GlobalParam;

/**
*
* @author wangchao
* @Version 1.0
* @date 2015-9-30 上午10:22:21
*/
public class TcpServer {
// private static final Logger logger = LoggerFactory.getLogger(TcpServer.class);
private static final Logger logger = Logger.getLogger(TcpServer.class);


/**
* 初始化服务 整行传输--new TextLineCodecFactory(Charset.forName( "UTF-8" ))
* @throws IOException
*/
public static void initialize() throws IOException {
// Create an Acceptor
NioSocketAcceptor acceptor = new NioSocketAcceptor();
// Add Handler
acceptor.setHandler(new TcpServerHandler());
//过滤器链
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//日志
LoggingFilter loggingFilter = new LoggingFilter();
loggingFilter.setSessionClosedLogLevel(LogLevel.NONE);
loggingFilter.setSessionCreatedLogLevel(LogLevel.DEBUG);
loggingFilter.setSessionOpenedLogLevel(LogLevel.INFO);
loggingFilter.setExceptionCaughtLogLevel(LogLevel.ERROR);
chain.addLast("logging", loggingFilter);
//黑名单
InetAddress[] addressArr = new InetAddress[]{};
BlacklistFilter blackList = new BlacklistFilter();
blackList.setBlacklist(addressArr);
chain.addLast("blackList", blackList);
//编码解码过滤器--普通字符串
chain.addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName( "UTF-8" ))));
//线程池
chain.addLast("threadPool",new ExecutorFilter(Executors.newCachedThreadPool()));
//session配置
SocketSessionConfig cfg = acceptor.getSessionConfig();
cfg.setReuseAddress(true);//设置复用地址
cfg.setReadBufferSize(GlobalParam.READ_BUFFER_SIZE);//读
cfg.setSendBufferSize(GlobalParam.SEND_BUFFER_SIZE);//写
cfg.setReceiveBufferSize(GlobalParam.RECEIVE_BUFFER_SIZE);//收
cfg.setIdleTime(IdleStatus.BOTH_IDLE, 2);

logger.info("Starting Server.... and then Listening on:"+GlobalParam.TCP_SHORT_SERVER_PORT);
//Bind地址
acceptor.bind(new InetSocketAddress(GlobalParam.TCP_SHORT_SERVER_PORT));
logger.info("Server listening on "+GlobalParam.TCP_SHORT_SERVER_PORT);
}



public static void main(String[] args) {
try {
initialize();
} catch (IOException e) {
logger.error("start Server is throw Exception ",e);
}
}
}

服务端Handler代码:
package com.tcp.server;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
*
* @author wangchao
* @Version 1.0
* @date 2015-9-30 上午10:22:14
*/
public class TcpServerHandler implements IoHandler{
private static final Logger logger = Logger.getLogger(TcpServer.class);

@Override
public void exceptionCaught(IoSession session, Throwable e)
throws Exception {
logger.debug(e.getMessage(),e);
// e.printStackTrace();
}

@Override
public void messageReceived(IoSession session, Object msg) throws Exception {
System.out.println("服务端:messageReceived..."+msg.toString());
session.write("{\"name\":\"aobama\"}");
}

@Override
public void messageSent(IoSession arg0, Object arg1) throws Exception {
// TODO Auto-generated method stub
logger.info("服务端:messageSent..."+getCurrentDate());
}

@Override
public void sessionClosed(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
logger.info("服务端:sessionClosed..."+getCurrentDate());
}

@Override
public void sessionCreated(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
// System.out.println("sessionCreated...");
logger.info("服务端:sessionCreated..."+getCurrentDate());
}

@Override
public void sessionIdle(IoSession session, IdleStatus arg1) throws Exception {
// TODO Auto-generated method stub
session.write("idle--"+getCurrentDate());
// logger.info("sessionIdle "+CommonsUtils.getCurrentDate());
}

@Override
public void sessionOpened(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
logger.info("服务端:sessionOpened..."+getCurrentDate());
}
@Override
public void inputClosed(IoSession arg0) throws Exception {
// TODO Auto-generated method stub

}

private static String getCurrentDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return sdf.format(new Date());
}
}

客户端Client代码:
package com.tcp.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcp.GlobalParam;
import com.tcp.server.TcpServer;

/**
*
* @author wangchao
* @Version 1.0
* @date 2015-9-30 上午10:21:59
*/
public class TcpClientDemo {
private static final Logger logger = LoggerFactory.getLogger(TcpServer.class);

public static void connectServer() throws IOException {
// Create an Acceptor
NioSocketConnector connector = new NioSocketConnector();
// Add Handler
connector.setHandler(new TcpClientDemoHandler());

//过滤器链
DefaultIoFilterChainBuilder chain = connector.getFilterChain();
//日志
chain.addLast("logging", new LoggingFilter());
//编码解码过滤器 Http
// chain.addLast("http",new HttpClientCodec());
chain.addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName( "UTF-8" ))));
// connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new MyProtocalCodecFactory("UTF-8")));
//线程池
chain.addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));

// Create Session Configuration
SocketSessionConfig cfg = connector.getSessionConfig();
cfg.setReuseAddress(true);
cfg.setReadBufferSize(GlobalParam.READ_BUFFER_SIZE);
cfg.setReceiveBufferSize(GlobalParam.RECEIVE_BUFFER_SIZE);
// cfg.setIdleTime(IdleStatus.BOTH_IDLE, 2);

logger.info("Starting client......");
System.out.println("Starting client.... and then connect to-- "+GlobalParam.TCP_SHORT_SERVER_HOST+":"+GlobalParam.TCP_SHORT_SERVER_PORT);
// Bind and be ready to listen
ConnectFuture cf = connector.connect(new InetSocketAddress(GlobalParam.TCP_SHORT_SERVER_HOST,GlobalParam.TCP_SHORT_SERVER_PORT));
//
// cf.awaitUninterruptibly();
// connector.dispose();
}


public static void main(String[] args) {
try {
connectServer();
} catch (IOException e) {
// e.printStackTrace();
logger.error("start Server is throw Exception ",e);
}
}
}

客户端Handler代码:
package com.tcp.client;

import java.util.Date;

import net.sf.json.JSONObject;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
*
* @author wangchao
* @Version 1.0
* @date 2015-9-30 上午10:22:06
*/
public class TcpClientDemoHandler implements IoHandler{

@Override
public void exceptionCaught(IoSession arg0, Throwable arg1)
throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:exceptionCaught...");
}

@Override
public void messageReceived(IoSession session, Object msg) throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:Client ---messageReceived...");
String str = msg.toString();
JSONObject json = JSONObject.fromObject(msg);
System.out.println("客户端:来至服务器的消息:"+str+" name:"+json.getString("name"));

// Date date = new Date();
// session.write(date.toString());
// System.out.println("Message written...");
// session.close(true);
}

@Override
public void messageSent(IoSession session, Object arg1) throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:messageSent...");
}

@Override
public void sessionClosed(IoSession arg0) throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:sessionClosed...");
}

@Override
public void sessionCreated(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:sessionCreated...");
session.write("sessionCreated客户端--"+new Date().toString());
}

@Override
public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:sessionIdle...");
}

@Override
public void sessionOpened(IoSession session) throws Exception {
// TODO Auto-generated method stub
System.out.println("客户端:sessionOpened...");
}

@Override
public void inputClosed(IoSession arg0) throws Exception {
// TODO Auto-generated method stub

}
}


常量信息类GlobalParam.java:
package com.tcp;

/**
*
* @author wangchao
* @Version 1.0
* @date 2015-9-30 上午9:40:49
*/
public class GlobalParam {
/**
* TCP短连接地址
*/
public static final String TCP_SHORT_SERVER_HOST = "127.0.0.1";
/**
* TCP短连接端口
*/
public static final int TCP_SHORT_SERVER_PORT = 8880;
/**
* TCP长连接地址
*/
public static final String TCP_LONG_SERVER_HOST = "127.0.0.1";
/**
* TCP长连接端口
*/
public static final int TCP_LONG_SERVER_PORT = 8881;
/**
* HTTP连接地址
*/
public static final String HTTP_SERVER_HOST = "127.0.0.1";
/**
* HTTP连接端口
*/
public static final int HTTP_SERVER_PORT = 8882;




/**
* 读-缓冲区大小,一次(2048byte)2K
*/
public static final int READ_BUFFER_SIZE = 2048;
/**
* 写-缓冲区大小,一次(2048byte)2K
*/
public static final int SEND_BUFFER_SIZE = 2048;
/**
* 收-缓冲区大小,一次(2048byte)2K
*/
public static final int RECEIVE_BUFFER_SIZE = 2048;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值