websocket

http://www.oschina.net/translate/java-ee-html5-websocket-example
    服务端代码:
    
  1. package com.byteslounge.websockets;
  2. import java.io.IOException;
  3. import javax.websocket.OnClose;
  4. import javax.websocket.OnMessage;
  5. import javax.websocket.OnOpen;
  6. import javax.websocket.Session;
  7. import javax.websocket.server.ServerEndpoint;
  8. @ServerEndpoint("/websocket")
  9. public class WebSocketTest {
  10. @OnMessage
  11. public void onMessage(String message, Session session)
  12. throws IOException, InterruptedException {
  13. // Print the client message for testing purposes
  14. System.out.println("Received: " + message);
  15. // Send the first message to the client
  16. session.getBasicRemote().sendText("This is the first server message");
  17. // Send 3 messages to the client every 5 seconds
  18. int sentMessages = 0;
  19. while(sentMessages < 3){
  20. Thread.sleep(5000);
  21. session.getBasicRemote().
  22. sendText("This is an intermediate server message. Count: "
  23. + sentMessages);
  24. sentMessages++;
  25. }
  26. // Send a final message to the client
  27. session.getBasicRemote().sendText("This is the last server message");
  28. }
  29. @OnOpen
  30. public void onOpen() {
  31. System.out.println("Client connected");
  32. }
  33. @OnClose
  34. public void onClose() {
  35. System.out.println("Connection closed");
  36. }
  37. }
    客户端代码:  
  1. var webSocket =
  2. new WebSocket('ws://localhost:8080/byteslounge/websocket');
  3. webSocket.onerror = function(event) {
  4. onError(event)
  5. };
  6. webSocket.onopen = function(event) {
  7. onOpen(event)
  8. };
  9. webSocket.onmessage = function(event) {
  10. onMessage(event)
  11. };
  12. function onMessage(event) {
  13. document.getElementById('messages').innerHTML
  14. += '<br />' + event.data;
  15. }
  16. function onOpen(event) {
  17. document.getElementById('messages').innerHTML
  18. = 'Connection established';
  19. }
  20. function onError(event) {
  21. alert(event.data);
  22. }
  23. function start() {
  24. webSocket.send('hello');
  25. return false;
  26. }





posted @ 2015-11-13 09:04  skyding  阅读(288)  评论(0)    收藏  举报