这是我的服务器的代码
package local.xx.mavenws;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import javax.enterprise.context.ApplicationScoped;
import org.joda.time.DateTime;
@ApplicationScoped
@ServerEndpoint("/")
public class Server {
private final ArrayList<Session> sessions;
public Server() {
this.sessions = new ArrayList<>();
}
@OnOpen
public void onOpen(Session session) {
this.sessions.add(session);
this.echo("Client connected!");
}
@OnClose
public void onClose(Session session) {
this.sessions.remove(session);
this.echo("Client disconnected!");
}
@OnError
public void onError(Throwable error) {
this.echo("Error occured!");
this.echo(error.getLocalizedMessage());
}
@OnMessage
public void onMessage(String message, Session session) {
try {
message = "[" + this.currentDate() + "] " + message;
this.echo(message);
for( Session sess : this.sessions ) {
sess.getBasicRemote().sendText(message);
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void echo(String info) {
System.out.println(info);
}
private String currentDate() {
String dateArray[] = (new DateTime()).toString().split("T");
String date = dateArray[0] + " " + (dateArray[1].split("\.")[0]);
return date;
}
}
我希望它向所有连接的用户发送收到的消息。问题是,它单独对待每个连接,就像每个连接都有自己的服务器实例一样。当我连接两个浏览器窗口时,消息分别显示。有人对此有什么想法吗?
终于搞定了!解决方案是,sessions
变量必须是静态的,我必须总是在Server
范围内调用它,而不是this
。这意味着,尽管为每个连接的用户创建了一个新的Server
实例,但变量对每个用户都是相互的。