iteye_12241
iteye_12241
2012-04-11 11:39
浏览 229
已采纳

关于Mina中服务器给客户端发送数据的问题

现在的要求是当客户端连接服务器后,发送“login”登陆报文,服务器接受到登陆消息后,就要给客户端一直发送数据。
请问应该怎么做?我开启了一个线程,然后给客户端发送消息,但是客户端收不到。

这个是我写的线程类
[code="java"]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;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    if(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 block
            e.printStackTrace();
        }
    }
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

}
[/code]

服务器端messageReceived方法,接受到登陆报文后,就一直给客户端发送消息
[code="java"]public void messageReceived(IoSession session, Object obj) throws Exception {
// TODO Auto-generated method stub
String 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.");
    }
}[/code]
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • iteye_13371
    iteye_13371 2012-04-12 02:48
    已采纳

    Runnable不能直接调用run(),应该调用start()

    点赞 评论

相关推荐