websocket
1.不是http协议
2.直接从服务器发送数据给客户端
3.不使用轮询
坑在使用的时候 以ws开头,使用js才能进行
与长短轮询的不同
1,长短轮询是从客户机不断地发送数据直接给服务器
2 。长与短的问题在于发送的频率
@ServerEndpoint("/websocket1")
public class WebSocketTest {
@OnMessage
public void onMessage(String message, Session session)
throws IOException, InterruptedException {
// Print the client message for testing purposes
System.out.println("Received: " + message);
// Send the first message to the client
session.getBasicRemote().sendText("This is the first server message");
// Send 3 messages to the client every 5 seconds
int sentMessages = 0;
while(sentMessages < 3){
Thread.sleep(5000);
session.getBasicRemote().
sendText("This is an intermediate server message. Count: "
+ sentMessages);
sentMessages++;
}
// Send a final message to the client
session.getBasicRemote().sendText("This is the last server message");
}
@OnOpen
public void onOpen () {
System.out.println("Client connected");
}
@OnClose
public void onClose () {
System.out.println("Connection closed");
}
}