问题描述
现在的要求是当客户端连接服务器后,发送“login”登陆报文,服务器接受到登陆消息后,就要给客户端一直发送数据。请问应该怎么做?我开启了一个线程,然后给客户端发送消息,但是客户端收不到。这个是我写的线程类public class SendMessageThread implements Runnable{private IoSession session = null;private String msg = null;public SendMessageThread(IoSession session) {this.session = session;}public SendMessageThread(IoSession session, String msg) {this.msg = msg;}@Overridepublic void run() {// TODO Auto-generated method stubif(null == msg) {msg = "test";}while(true) {System.out.println(new Date()+":"+msg);session.write(new Date()+":"+msg);try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}服务器端messageReceived方法,接受到登陆报文后,就一直给客户端发送消息public void messageReceived(IoSession session, Object obj) throws Exception {// TODO Auto-generated method stubString msg = (String)obj;System.out.println("服务器收到:"+msg);if(msg.equalsIgnoreCase("login")) {System.out.println("用户登陆");session.write("nihao");session.write("nono");new SendMessageThread(session).run();} else {System.out.println("Undefined operation.");}}
解决方案
Runnable不能直接调用run(),应该调用start()