DIV CSS 佈局教程網

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

第六步:JavaScript

首先把代碼放進 jQuery 的 document.ready 函數,再檢查用戶瀏覽器是否支援 Web Socket。若不支援,就加上一個指向 Chrome 頁面下載的鏈接。

  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...</p>').appendTo('#container');
  5. }else{
  6. connect();
  7. function connect(){
  8. //the connect function code is below
  9. }
  10. }
  11. });

若瀏覽器支援 Web Socket,我們就執行 connect() 函數。這裡是核心功能,我們要開始建立 open、close 與 receive 事件,並定義服務器的 URL。

  1. var socket;
  2. var host = "ws://localhost:8000/socket/server/startDaemon.php";

你可能會注意到 URL 裡怎麼沒有 http?是的,這是 Web Socket URL,使用不同的協議。

接著完成 connect() 函數。把代碼放進 try/catch 塊,這樣出問題時能讓用戶知道。我們建立 Web Socket 並把信息傳給 message() 函數,同時建立 onopen、onmessage 與 onclose。這裡為用戶提供了端口狀態,雖非必需,但方便調試。

  1. CONNECTING = 0
  2. OPEN = 1
  3. CLOSED = 2
  4. function connect(){
  5. try{
  6. var socket = new WebSocket(host);
  7. message('<p class="event">Socket Status: '+socket.readyState);
  8. socket.onopen = function(){
  9. message('<p class="event">Socket Status: '+socket.readyState+' (open)');
  10. }
  11. socket.onmessage = function(msg){
  12. message('<p class="message">Received: '+msg.data);
  13. }
  14. socket.onclose = function(){
  15. message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
  16. }
  17. } catch(exception){
  18. message('<p>Error'+exception);
  19. }
  20. }

message() 函數很簡單,它把要展示給用戶的文字填進 chat log 容器,我們在 socket 事件函數中為段落標籤建立適當的 class。

  1. function message(msg){
  2. $('#chatLog').append(msg+'</p>');
  3. }

目前的成果:你已建立 HTML/CSS 模板、建立 Web Socket 連接,並能透過連接更新用戶進度。

第七步:發送數據

我們需要監聽用戶按下鍵盤的事件並運行 send 函數,13 便是回車鍵對應的 ASCII 碼。

  1. $('#text').keypress(function(event) {
  2. if (event.keyCode == '13') {
  3. send();
  4. }
  5. });

send() 函數如下:

  1. function send(){
  2. var text = $('#text').val();
  3. if(text==""){
  4. message('<p class="warning">Please enter a message');
  5. return ;
  6. }
  7. try{
  8. socket.send(text);
  9. message('<p class="event">Sent: '+text)
  10. } catch(exception){
  11. message('<p class="warning"> Error:' + exception);
  12. }
  13. $('#text').val("");
  14. }

這些額外的代碼還負責檢測用戶是否空白輸入、清空輸入框,並執行 message() 函數。

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