socket.io 官網翻譯1——Get started/chat

socket.io很是適合作聊天室,但英文官網讀起來仍是有必定的障礙,特此翻譯。若有誤點,歡迎指出。html

原地址:http://socket.io/get-started/chat/node

正文以下:jquery

開始:聊天

本篇文章,咱們將一塊兒來建立一個簡單的聊天應用。它幾乎不要求你提早掌握Node.JS 或 Socket.IO的知識,適合任何人來嘗試。git

介紹

用LAMP這種傳統的方式來搭建一個聊天應用是很難的,它包括輪詢服務器的變化,保持跟蹤時間戳,比socket.io慢得多。github

Sockets一直是最具實時性的聊天系統解決方案,在客戶端和服務端提供了一種雙向通訊通道。web

這意味着服務器能發送消息給客戶端。當你發出一條消息時,服務端將獲取它,並將它發送給其餘全部在線客戶端。express

使用web框架 express

首要目標是創建一個簡單的HTML頁面,包括一個表單和一個消息列表,咱們將使用Node.JS web 框架 express 去搭建。請先確保 Node.JS 已經安裝。npm

首先爲咱們的應用新建一個package.json配置文件,把它放到一個新建的文件夾中(例如chat-example)。編程

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {}
}

如今爲了更快的將咱們須要的依賴應用添加到dependencies中,運行npm install --savejson

npm install --save express@4.10.2

如今express已經安裝好了,咱們再新建一個index.js做爲咱們的入口文件。

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
  res.send('<h1>Hello world</h1>');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

說明以下:

  1. Express初始化app爲一個處理請求HTTP服務的程序。(參見第二行)

  2. 定義一個路由/訪問網站根目錄

  3. 監聽HTTP服務器端口3000

若是你運行node index.js,將看到以下界面:
圖片描述

緊接着咱們用瀏覽器訪問http://localhost:3000
圖片描述

編輯HTML(Serving HTML)

如今咱們在index.js中使用res.send傳遞一個HTML字符串。若是咱們把整個應用的的HTML放在index.js中,整個代碼結構將雜亂無章。因此咱們要建立一個index.html文件。

咱們要使用sendFile方法來重構路由管理。

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

index.html以下:

<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

若是你重啓進程(ctrl+C並再次運行node index)而且刷新瀏覽器,效果以下:

圖片描述

整合Socket.IO

Socket.IO由兩部分構成:

  • 服務端使用Node.JS的HTTP服務器: socket.io

  • 客戶端則在瀏覽器端加載:socket.io-client

開發期間,socket.io自動在客服端運行加載,如今咱們必需要安裝一個模塊:

npm install --save socket.io

上面的命令將安裝socket.io模塊,並將它寫入配置文件package.json。而後咱們修改index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

注意,我經過使用http(http服務器)對象來初始化一個socket.io實例。接着監聽socket鏈接事件,並將它輸出到控制檯。

而後在index.html</body>以前加入如下片斷:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>

客戶端加載socket.io-client,在全局調用io()並鏈接服務端。

注意,當咱們調用io()時沒有指定任何一個URL,由於它默認去嘗試鏈接主機。

若是你如今重載服務器和客戶端,控制檯打印「a user connected」。

嘗試打開多個頁面,你將看到如:

圖片描述

每一個socket也觸發特殊的disconnect事件。

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

若是你刷新一個頁面幾回,你將在控制檯看到以下信息:

圖片描述

發送事件(Emitting)

Socket.IO背後的主要思想是:你能夠發送和接收任何你想要的事件和數據。任何被編碼爲JSON的對象,二進制數據也支持。

當用戶輸入一條消息時,服務端把它看成chat message事件得到。在index.html中的script片斷以下:

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  var socket = io();
  $('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
  });
</script>

同時在index.js中打印出chat message事件:

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});

結果以下:(原文是一小片斷視頻,此處沒法加進來,截圖展現)

圖片描述

通知(Broadcasting)

下一個目標是未來自服務器的消息發送給其餘用戶。

爲了發送給每個人,Socket.IO提供io.emit了給咱們:

io.emit('some event', { for: 'everyone' });

若是你想發送消息給每一個人除了必定的socket,咱們有broadcast標記:

io.on('connection', function(socket){
  socket.broadcast.emit('hi');
});

如今爲了簡單起見,咱們發送消息給每一個人,包括髮送者本身。

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

在客戶端咱們捕獲chat message事件。客戶端所有的 JavaScript 代碼以下:

<script>
  var socket = io();
  $('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
  });
  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
</script>

如今咱們的聊天應用完成了,大約20行代碼,最後就是這樣子了:(原文是一小片斷視頻,此處沒法加進來,截圖展現)

圖片描述

更多的實踐

這有一些建議來改進這個應用:

  • 當有人進入或離開時,通知給全部人。

  • 增長暱稱

  • 不發送相同的消息給發送者本身,反而當輸入回車時快速發送消息。

  • 增長「用戶正在輸入」功能

  • 展現誰在線

  • 增長私信

  • 分享你的改進

得到這個例子

在GitHub上你能找到它

$ git clone https://github.com/guille/chat-example.git

譯者說:

這篇文章仍是有幾處我沒有翻譯好的地方,做爲一個coder必需要把英語學好。好事多磨,編程也不要過度地追求速度。

相關文章
相關標籤/搜索