minaTcpインスタンス
14476 ワード
tcp接続プロトコルの例.
完全なコードは添付ファイルにダウンロードしてください.
サービス側を直接起動し、クライアントを起動すればよい.
//サービス側印刷情報:
//クライアント印刷情報:
サービス側サーバコード
サービス側Handlerコード:
クライアントClientコード:
クライアントHandlerコード:
定数情報クラスGlobalParam.java:
完全なコードは添付ファイルにダウンロードしてください.
サービス側を直接起動し、クライアントを起動すればよい.
//サービス側印刷情報:
[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...
サービス側サーバコード
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;
}