版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/github_34402358/article/details/80624170
服务器端使用jar: mina-core-2.0.18.jar slf4j-api-1.7.25.jar
public class MinaServer {
// 端口号,要求客户端与服务器端一致
private static int PORT = 8282;
public static void main(String[] args) {
IoAcceptor acceptor = null;
try {
// 创建一个非阻塞的server端的Socket
acceptor = new NioSocketAcceptor();
// 设置过滤器(使用mina提供的文本换行符编解码器)
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter((ProtocolCodecFactory) new TextLineCodecFactory(Charset.forName("UTF-8"),
LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue())));
// 设置读取数据的换从区大小
acceptor.getSessionConfig().setReadBufferSize(2048);
// 读写通道10秒内无操作进入空闲状态
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 15);
// 为接收器设置管理服务
acceptor.setHandler(new MinaServerHandler());
// 绑定端口
acceptor.bind(new InetSocketAddress(PORT));
System.out.print("服务器启动成功... 端口号未:" + PORT);
} catch (Exception e) {
System.out.print("服务器启动异常..." + e.toString());
e.printStackTrace();
}
}
}
import java.util.Date;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
public class MinaServerHandler extends IoHandlerAdapter {
// 从端口接受消息,会响应此方法来对消息进行处理
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
String msg = message.toString();
if ("exit".equals(msg)) {
// 如果客户端发来exit,则关闭该连接
session.closeNow();
}
// 向客户端发送消息
Date date = new Date();
session.write(date);
System.out.print("服务器接受消息成功...\n");
super.messageReceived(session, message);
}
// 向客服端发送消息后会调用此方法
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.print("服务器发送消息成功...\n");
super.messageSent(session, message);
}
// 关闭与客户端的连接时会调用此方法
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.print("服务器与客户端断开连接...\n");
super.sessionClosed(session);
}
// 服务器与客户端创建连接
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.print("\n服务器与客户端创建连接...\n");
super.sessionCreated(session);
}
// 服务器与客户端连接打开
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.print("服务器与客户端连接打开...\n");
super.sessionOpened(session);
}
// 服务器状态
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
System.out.print("服务器进入空闲状态...\n");
super.sessionIdle(session, status);
}
// 服务器发送异常态
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
System.out.print("服务器发送异常...\n");
super.exceptionCaught(session, cause);
}
}
浏览器中输入:http://localhost:8282 点击回车
到此为止,服务器端就完成了!!!!!!