mina socket 模拟多个client发送多条消息到服务器怎么做
1个回答
展开全部
建立 ClientHandler 类
public class ClientHandler extends IoHandlerAdapter {
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
@Override
public void messageReceived(IoSession iosession, Object message)
throws Exception {
String str=message.toString();
if(str.trim().equals("quit")){
iosession.close(true);
return;
}
Date date=new Date();
iosession.write(date.toString());
System.out.println("message written...");
}
@Override
public void sessionIdle(IoSession iosession,IdleStatus status){
System.out.println("IDLE "+iosession.getIdleCount(status));
}
@Override
public void messageSent(IoSession iosession, Object message) throws Exception {
System.out.println("send messages");
}
}
在 Client 实现的类里
try {
address = new InetSocketAddress("IP地址", 端口);
connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory()));
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.setHandler(handler);
future1 = connector.connect(address);
future1.awaitUninterruptibly();
if (!future1.isConnected()) {
System.out.println("not connect");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
然后new 几个 client类 就行
public class ClientHandler extends IoHandlerAdapter {
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
cause.printStackTrace();
}
@Override
public void messageReceived(IoSession iosession, Object message)
throws Exception {
String str=message.toString();
if(str.trim().equals("quit")){
iosession.close(true);
return;
}
Date date=new Date();
iosession.write(date.toString());
System.out.println("message written...");
}
@Override
public void sessionIdle(IoSession iosession,IdleStatus status){
System.out.println("IDLE "+iosession.getIdleCount(status));
}
@Override
public void messageSent(IoSession iosession, Object message) throws Exception {
System.out.println("send messages");
}
}
在 Client 实现的类里
try {
address = new InetSocketAddress("IP地址", 端口);
connector.getFilterChain().addLast("mdc", new MdcInjectionFilter());
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory()));
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.setHandler(handler);
future1 = connector.connect(address);
future1.awaitUninterruptibly();
if (!future1.isConnected()) {
System.out.println("not connect");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
然后new 几个 client类 就行
追问
可能描述的问题, 我想实现多个客户端,这多个客户端连接服务器后,每个客户端要不停的发消息到服务端, 我这里就差每个客户端不停地发消息这一步了不能实现了。我看了您贴出来的代码了,不能实现每个客户端不停地想服务器发消息。
追答
client类就是个连接的类啊
在类里建立一个Timer定时器 每隔指定秒数就执行
session.write("发送的消息");
就好了
一个类实例 就会建立以个客户端
你new 10个client类实例 就是10个客户端
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询