web服务器:tomcat8,用eclipse开发,导入了websocket需要的jar包,建立连接成功,但是在后台终端向前台发送数据时候,出现
Uncaught TypeError: Cannot set property 'onmessage' of null
已经查阅网上各种有关资料了,依然不能解决这个问题,希望大神帮忙看下哪里出问题了。下面贴出代码
前端代码:
<script type="text/javascript">
//建立websocket对象
var chat={};
chat.socket=null;
var uname='<%=request.getSession().getAttribute("uname")%>';
function conn() {
//执行建立连接
connect("ws://localhost:8085/chat/begin?uname="+uname);
chat.socket.onmessage=function(event){
console.log(event.data)
}
}
function connect(host){
if("WebSocket" in window){
socket=new WebSocket(host);
}else if("MoWebSocket" in window){
socket=new MoWebSocket(host);
}else{
console.log("当前浏览器不支持socket");
return;
}
}
</script>
后台终端代码:
@ServerEndpoint("/begin")
public class ChatServer {
Session session;
private String uname;
private static Map<String,ChatServer> member=new HashMap<String,ChatServer>();
@OnOpen
public void start(Session session){
this.session=session;
String []art=session.getQueryString().split("=");
System.out.println(art[1]);
if(art.length>=2){
this.uname=art[1];
member.put(uname, this);
}
}
private void welcome(){
for(ChatServer mem: member.values()){
if(mem==this){
this.send("欢迎您登录成功");
}else{
mem.send("欢迎"+this.uname+"登录");
}
}
}
private void send(String message){
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ServerApplicationConfig:
public class Scanner implements ServerApplicationConfig{
@Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> arg0) {
return arg0;
}
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) {
return null;
}
}