使用Mina客户端如何和服务端建立长连接,给个示例
时间: 2024-05-04 10:22:44 浏览: 195
好的,以下是一个示例:
客户端代码:
```java
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
public class MyClient {
private static final String HOSTNAME = "localhost"; // 服务端地址
private static final int PORT = 12345; // 服务端端口号
public static void main(String[] args) {
IoConnector connector = new NioSocketConnector();
connector.setConnectTimeoutMillis(30000); // 连接超时时间
connector.setHandler(new MyClientHandler()); // 设置消息处理器
ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT)); // 连接服务端
future.awaitUninterruptibly(); // 等待连接完成
IoSession session = future.getSession(); // 获取会话
session.getCloseFuture().awaitUninterruptibly(); // 等待会话关闭
connector.dispose(); // 关闭连接器
}
}
```
服务端代码:
```java
import java.net.InetSocketAddress;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
public class MyServer {
private static final int PORT = 12345; // 监听端口号
public static void main(String[] args) throws Exception {
IoAcceptor acceptor = new NioSocketAcceptor(); // 创建连接器
acceptor.setHandler(new MyServerHandler()); // 设置消息处理器
acceptor.bind(new InetSocketAddress(PORT)); // 绑定监听端口号
System.out.println("Server started on port " + PORT);
acceptor.dispose(); // 关闭连接器
}
}
```
阅读全文