DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
HTML 5 Web Sockets 應用初探(4)
編輯:CSS詳解     

第八步:關閉 Socket

關閉 Socket 操作相當簡單,只需為斷開連接按鈕添加 click 事件監聽即可。

  1. $('#disconnect').click(function(){
  2. socket.close();
  3. });

完整 JavaScript 代碼

  1. $(document).ready(function() {
  2. if(!("WebSocket" in window)){
  3. $('#chatLog, input, button, #examples').fadeOut("fast");
  4. $('<p>Oh no, you need a browser that supports Web Sockets. How about <a href="https://www.google.com/Chrome">Google Chrome</a>?</p>').appendTo('#container');
  5. }else{
  6. connect();
  7. function connect(){
  8. var socket;
  9. var host = "ws://localhost:8000/socket/server/startDaemon.php";
  10. try{
  11. var socket = new WebSocket(host);
  12. message('<p class="event">Socket Status: '+socket.readyState);
  13. socket.onopen = function(){
  14. message('<p class="event">Socket Status: '+socket.readyState+' (open)');
  15. }
  16. socket.onmessage = function(msg){
  17. message('<p class="message">Received: '+msg.data);
  18. }
  19. socket.onclose = function(){
  20. message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
  21. }
  22. } catch(exception){
  23. message('<p>Error'+exception);
  24. }
  25. function send(){
  26. var text = $('#text').val();
  27. if(text==""){
  28. message('<p class="warning">Please enter a message');
  29. return ;
  30. }
  31. try{
  32. socket.send(text);
  33. message('<p class="event">Sent: '+text)
  34. } catch(exception){
  35. message('<p class="warning">');
  36. }
  37. $('#text').val("");
  38. }
  39. function message(msg){
  40. $('#chatLog').append(msg+'</p>');
  41. }
  42. $('#text').keypress(function(event) {
  43. if (event.keyCode == '13') {
  44. send();
  45. }
  46. });
  47. $('#disconnect').click(function(){
  48. socket.close();
  49. });
  50. }
  51. }
  52. });

第九步:運行 Web Socket 服務器

XAMPP 提供了方便的 shell 選項,點擊控制面板的 shell 按鈕並輸入:

  1. php -q path\to\server.php

現在你已經運行了 Web Socket 服務器!

大功告成!

當頁面讀取後,會嘗試建立一個 Web Socket 連接,之後用戶就能輸入信息並從服務器接收信息。想了解更多,可參考 The Web Socket API 的最新動態。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved