• socket.io 中文案例文档 (官方socket.io聊天应用demo)


    英文原文   http://socket.io/get-started/chat/

    Get Started: Chat application

    In this guide we’ll create a basic chat application. It requires almost no basic prior knowledge of Node.JS or Socket.IO, so it’s ideal for users of all knowledge levels.

    开始:聊天应用

    在这个教程,我们将创建一个基本的聊天应用。它几乎不需要前置基础的Node.js或者Socket.IO知识,所以它适合所有知识层次的用户人群。

    Introduction

    Writing a chat application with popular web applications stacks like LAMP (PHP) has traditionally been very hard. It involves polling the server for changes, keeping track of timestamps, and it’s a lot slower than it should be.

    Sockets have traditionally been the solution around which most realtime chat systems are architected, providing a bi-directional communication channel between a client and a server.

    This means that the server can push messages to clients. Whenever you write a chat message, the idea is that the server will get it and push it to all other connected clients.

    介绍

    使用LAMP(PHP)那样的流行的web应用写一个聊天应用通常是很难的。它包含轮询服务器的变化,记录时间戳,并且它比实际会慢很多。

    Sockets 通常作为大多数实时聊天系统的解决方案被架构,提供一个连接服务器和客户端的双向通讯通道。

    这个意味着服务器能够推送消息到客户端。当你写一个聊天消息,服务器将获取它,并且推送它到所有的连接着的客户端。

    The web framework

    The first goal is to setup a simple HTML webpage that serves out a form and a list of messages. We’re going to use the Node.JS web framework express to this end. Make sure Node.JS is installed.

    First let’s create a package.json manifest file that describes our project. I recommend you place it in a dedicated empty directory (I’ll call mine chat-example).

    web框架

    第一步是设置一个简单的HTML页面,提供一个表单和一个消息列表。为此,我们将使用Node.JS的express框架。请确保Node.JS 已经安装.

    首先,我们创建package.json清单文件,描述我们的项目。我建议你将它置于一个专用的空的文件夹中(称为chat-example)

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

    Now, in order to easily populate the dependencies with the things we need, we’ll use npm install --save:

    现在,为了方便的移植我们需要的依赖项,我们将使用 npm install --save命令。

    npm install --save express@4.10.2

    Now that express is installed we can create an index.js file that will setup our application.

    现在,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');
    });

    This translates into the following:

    1. Express initializes app to be a function handler that you can supply to an HTTP server (as seen in line 2).

    2. We define a route handler / that gets called when we hit our website home.

    3. We make the http server listen on port 3000.

    If you run node index.js you should see the following:

    以下是代码介绍:

    1. Express 初始化app 作为函数处理器,你能够提供给HTTP服务器 (第二行).

    2. 我们定义一个路由处理器 / 用来访问我们站点的主页.

    3. 我们让http服务器侦听3000端口.

    如果你运行 node index.js 你将看到如下:

    And if you point your browser to http://localhost:3000:

    如果你通过你的浏览器访问http://localhost:3000:

    Serving HTML

    提供HTML

    So far in index.js we’re calling res.send and pass it a HTML string. Our code would look very confusing if we just placed our entire application’s HTML there. Instead, we’re going to create a index.html file and serve it.

    Let’s refactor our route handler to use sendFile instead:

    到目前为止,在index.js 中,我们调用res.send,并且传递给它一个HTML字符串。如果我们仅仅将整个应用的HTML置于这里,我的代码将看上去令人沮丧。替代,我们将创建一个index.html文件,并且提供它。

    让我们用sendfile替代重构路由处理器。

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

    And populate index.html with the following:

    并且用以下代码填入index.html:

    <!doctype 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;  100%; }
          form input { border: 0; padding: 10px;  90%; margin-right: .5%; }
          form button {  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>

    If you restart the process (by hitting Control+C and running node index again) and refresh the page it should look like this:

    如果你重启进程( Control+C 并且再次 node index) 并且刷新页面,你将看到如下:

    Integrating Socket.IO

    集成Socket.IO

    Socket.IO is composed of two parts:

    • A server that integrates with (or mounts on) the Node.JS HTTP Server: socket.io

    • A client library that loads on the browser side: socket.io-client

    During development, socket.io serves the client automatically for us, as we’ll see, so for now we only have to install one module:

    Socket.IO 由两方面组成:

    • 一个服务器,集成了(或者挂载了)Node.JS HTTP Server: socket.io

    • 浏览器端加载了客户端库: socket.io-client

    随着发展,socket.io 自动为我们提供了客户端库。我们就会看到,我们仅仅只需下载一个模块:

    npm install --save socket.io

    That will install the module and add the dependency to package.json. Now let’s edit index.js to add it:

    那样将安装模块,并且在package.json添加dependency 。现在我们编辑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');
    });

    Notice that I initialize a new instance of socket.io by passing the http (the HTTP server) object. Then I listen on theconnection event for incoming sockets, and I log it to the console.

    Now in index.html I add the following snippet before the </body>:

    注意,我们通过传递http对象(HTTP服务器)初始化了一个新的socket.io实例. 然后,我们侦听到来的socket连接事件,并且记录它到控制台.

    现在我们在index.html的<body>标签前面添加如下代码段:

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

    That’s all it takes to load the socket.io-client, which exposes a io global, and then connect.

    Notice that I’m not specifying any URL when I call io(), since it defaults to trying to connect to the host that serves the page.

    If you now reload the server and the website you should see the console print “a user connected”.
    Try opening several tabs, and you’ll see several messages:

    这样就加载了socket.io-client,暴露了一个io全局变量,并且连接。

    注意,我们当我们调用io(),没有指定任何URL,这样它默认尝试连接提供页面的主机。

    如果你现在重启服务器,并且网站你将看到控制台打印出“a user connected”.

    尝试打开多个网页标签,你将看到多条记录如下:

    Each socket also fires a special disconnect event:

    每个socket也会复发一个特别的disconnect事件:

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

    Then if you refresh a tab several times you can see it in action:

    如果你刷新页面,几秒钟后你能看到如下动作:

    Emitting events

    The main idea behind Socket.IO is that you can send and receive any events you want, with any data you want. Any objects that can be encoded as JSON will do, and binary data is supported too.

    Let’s make it so that when the user types in a message, the server gets it as a chat message event. The scripts section inindex.html should now look as follows:

    触发事件

    在Socket.IO之前主要的想法是,你能够传递和接收任意你想要的事件,任意你想要的数据。任意对象能够转码为JSON,并且二进制数据也是支持的。

    让我们当用户键入消息,服务器作为chat message事件获取它。index.html中的脚本段落现在应该像如下样子:

    <script src="/socket.io/socket.io.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>

    And in index.js we print out the chat message event:

    并且在index.js中,我们打印出chatmessage事件:

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

    The result should be like the following :

    结果应该像如下样子:

    blob.png

    blob.png

    Broadcasting

    广播

    The next goal is for us to emit the event from the server to the rest of the users.

    In order to send an event to everyone, Socket.IO gives us the io.emit:

    下一步,我们从服务器发射事件到其他用户.

    为了能够发射一个事件给所有人, Socket.IO 给了我们 io.emit:

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

    If you want to send a message to everyone except for a certain socket, we have the broadcast flag:

    如果你想要发射一个消息给所有人,而非某一个socket,我们有broadcast 标志:

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

    In this case, for the sake of simplicity we’ll send the message to everyone, including the sender.

    在这个案例中,为了简单的目的,我们发送消息给所有人,包括发送者。

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

    And on the client side when we capture a chat message event we’ll include it in the page. The total client-side JavaScript code now amounts to:

    在客户端,当我们捕获到一个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>

    And that completes our chat application, in about 20 lines of code! This is what it looks like:

    现在完成了我们的聊天应用。仅仅只需20行的代码!这个的样子如下:

    blob.png

    Getting this example

    You can find it on GitHub here.

    $ git clone https://github.com/guille/chat-example.git
  • 相关阅读:
    jQuery Ajax 实例 全解析
    简易的AJAX工具[转]
    一些JSON 教程
    写一个ajax程序就是如此简单
    ecshop中ajax的调用原理 1
    ECSHOP中ajax的调用原理
    ul中li分列显示
    PHP serialize & JSON 解析
    c++字符集之间转换(UTF-8,UNICODE,Gb2312)
    各种字符集和编码直接的联系详解
  • 原文地址:https://www.cnblogs.com/wjlbk/p/12633331.html
Copyright © 2020-2023  润新知