首页 > Web开发 > 详细

websocket

时间:2015-11-13 10:23:00      阅读:408      评论:0      收藏:0      [点我收藏+]
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. }





websocket

原文:http://www.cnblogs.com/vvch/p/4961132.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!