首页>代码>apache mina入门教程hello world简单实例源代码下载>/zuidaima_mina_helloworld/src/main/java/com/zuidaima/mina/server/HelloWorldServer.java
package com.zuidaima.mina.server; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.common.DefaultIoFilterChainBuilder; import org.apache.mina.common.IoAcceptor; import org.apache.mina.common.IoAcceptorConfig; import org.apache.mina.common.IoHandlerAdapter; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.SocketAcceptor; import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; public class HelloWorldServer { private static final int PORT = 8080; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { IoAcceptor acceptor = new SocketAcceptor(); IoAcceptorConfig config = new SocketAcceptorConfig(); DefaultIoFilterChainBuilder chain = config.getFilterChain(); // 使用字符串编码 chain.addLast("codec", new ProtocolCodecFilter( new TextLineCodecFactory())); // 启动HelloServer acceptor.bind(new InetSocketAddress(PORT), new HelloHandler(), config); System.out.println("HelloServer started on port " + PORT); } } /** * HelloServer的处理逻辑 * * @author liudong */ class HelloHandler extends IoHandlerAdapter { /** * 当有异常发生时触发 */ @Override public void exceptionCaught(IoSession ssn, Throwable cause) { cause.printStackTrace(); ssn.close(); } /** * 有新连接时触发 */ @Override public void sessionOpened(IoSession ssn) throws Exception { System.out.println("session open for " + ssn.getRemoteAddress()); } /** * 连接被关闭时触发 */ @Override public void sessionClosed(IoSession ssn) throws Exception { System.out.println("session closed from " + ssn.getRemoteAddress()); } /** * 收到来自客户端的消息 */ public void messageReceived(IoSession ssn, Object msg) throws Exception { String ip = ssn.getRemoteAddress().toString(); System.out.println("===> Message From " + ip + " : " + msg); ssn.write("Hello " + msg); } }
最近下载更多
爱情戴罪的羔羊 LV7
2021年1月14日
wen332 LV6
2019年1月4日
usan168 LV2
2018年5月26日
cuixiuquan LV5
2018年5月10日
jic499 LV27
2018年4月14日
864428652 LV10
2018年4月7日
苗毅6666 LV32
2018年3月31日
farwang2018 LV1
2018年3月23日
dagf113225 LV68
2017年8月30日
mzoai LV19
2017年6月27日
最近浏览更多
爱情戴罪的羔羊 LV7
2021年1月14日
Q375892799 LV9
2020年11月24日
guaixia163 LV13
2020年9月3日
陈齐尧 LV11
2020年7月16日
欠踹de背影 LV25
2020年6月5日
chokkint LV12
2020年5月20日
zzgover LV4
2020年4月3日
jessia LV4
2020年3月17日
myll23 LV1
2020年2月25日
FlamingYouth LV6
2020年2月2日