美文网首页
node搭建简单的websocket服务

node搭建简单的websocket服务

作者: 曾经也是个少年 | 来源:发表于2019-05-30 15:02 被阅读0次

Web框架

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

首先,让我们创建一个package.json描述我们项目的清单文件。我建议你把它放在一个专门的空目录中(我会打电话给我chat-example)。

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

现在,为了轻松填充dependencies我们需要的东西,我们将使用npm install --save

npm install --save express@4.15.2

现在已经安装了express,我们可以创建一个index.js将设置我们的应用程序的文件。

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

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

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

这转化为以下内容:

  • Express初始化app为可以提供给HTTP服务器的函数处理程序(如第2行所示)。
  • 我们定义一个路由处理程序/,当我们访问我们的网站时,它会被调用
  • 我们使http服务器侦听端口3000。

如果你跑步,node index.js你应该看到以下内容:

控制台说服务器已开始侦听端口3000

如果您将浏览器指向http://localhost:3000

一个显示大“Hello World”的浏览器

提供HTML

到目前为止,index.js我们正在调用res.send并传递一个HTML字符串。如果我们将整个应用程序的HTML放在那里,我们的代码看起来会很混乱。相反,我们将创建一个index.html文件并提供服务。

让我们重构我们的路由处理程序来sendFile代替:

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

并填充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; 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 Server集成(或安装)的服务器:socket.io
  • 在浏览器端加载的客户端库:socket.io-client

在开发过程中,socket.io正如我们所见,我们会自动为客户服务,所以现在我们只需要安装一个模块:

npm install --save 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(__dirname + '/index.html');
});

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

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

请注意,我socket.io通过传递http(HTTP服务器)对象来初始化新实例。然后我在connection事件上监听传入的套接字,然后将其记录到控制台。

现在在index.html中,我在以下内容之前添加以下代码段</body>

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

这就是加载它所需的全部内容socket.io-client,它暴露了io全局(和端点GET /socket.io/socket.io.js),然后连接。

如果您想使用本地版本的客户端JS文件,可以在以下位置找到它node_modules/socket.io-client/dist/socket.io.js

请注意,我在调用时没有指定任何URL io(),因为它默认尝试连接到为页面提供服务的主机。

如果您现在重新加载服务器和网站,您应该看到控制台打印“用户已连接”。

尝试打开几个标签,您会看到几条消息:

[图片上传失败...(image-bf7c81-1559199685037)]

每个插座也会触发一个特殊disconnect事件:

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

然后,如果您多次刷新选项卡,则可以看到它的运行情况:

控制台显示多条消息,表示某些用户已连接和断开连接

发出事件

Socket.IO背后的主要思想是,您可以使用您想要的任何数据发送和接收您想要的任何事件。任何可以编码为JSON的对象都可以,并且也支持二进制数据

让我们这样做,以便当用户键入消息时,服务器将其作为chat message事件获取。将script在S部件index.html现在应该如下所示:

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      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);
  });
});

结果应如下视频:

广播

下一个目标是让我们从服务器向其他用户发出事件。

为了向所有人发送活动,Socket.IO给了我们io.emit

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

如果你想向除了某个套接字以外的所有人发送消息,我们有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>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>

这完成了我们的聊天应用程序,大约20行代码!这就是它的样子:

相关文章

网友评论

      本文标题:node搭建简单的websocket服务

      本文链接:https://www.haomeiwen.com/subject/uehvtctx.html