新手指南:socket.IO

2025-05-25

新手指南:socket.IO

指导

  1. 介绍
  2. 会发生什么?
  3. 概括
  4. 设置主项目目录
  5. 安装依赖项
  6. 目录结构
  7. 在index.js中创建服务器
  8. 设置index.html
  9. 测试你的服务器 10. 建立你的第一个套接字连接
  10. 结论
  11. 资源

注意:本指南涵盖了设置要使用的 socket.IO 的步骤。使用 socket.IO 的聊天应用将在第二部分介绍。

介绍

Socket.IO 是一个 JavaScript 库,支持实时双向通信。这意味着速度极快!而且无需重新加载页面。Socket.IO 基于 WebSockets API,允许服务器和客户端之间建立直接通信隧道,并保持畅通。

用图表来代替这个:

我们现在有:

因此服务器无法自行向客户端发送消息。必须刷新浏览器,然后向服务器请求消息。然而,sockets.io 允许即时通信。

当我们从浏览器请求 URL 时,我们会打开与服务器的聊天套接字连接。

会发生什么?

  • 数据在客户端和服务器之间来回流动
  • 客户端“A”向服务器发送消息
  • 聊天服务器收到消息
  • 服务器决定将消息发送给所有连接的客户端,以便他们可以看到客户端“A”发送的消息

概括

总结:

  • Sockets.io 是一个 JS 库
  • 实现双边通信
  • 客户端与服务器实时同步通信
  • 基于其他实时协议(例如 websockets API)构建
  • 事件驱动
  • 包含 2 个部分:1. 浏览器中的客户端库 2. Node 的服务器端库

因此,使用 socket.IO 时,您需要同时处理两个文件,例如 chat.js(客户端)和 index.js(服务器端)。
这是因为您必须编写代码/逻辑来从服务器/客户端发送消息,然后在另一端(即客户端/服务器)接收消息。

设置主项目目录

//make a new folder
mkdir chat_app

//navigate to the folder
cd chat_app

Enter fullscreen mode Exit fullscreen mode

安装依赖项

在终端中使用 npm 安装依赖项。首先检查是否已安装 node 和 npm:

node -v
npm -v

Enter fullscreen mode Exit fullscreen mode

初始化 npm

//create the package JSON file which will list all the dependencies used in the project
//leave index.js as the entry point
npm init

Enter fullscreen mode Exit fullscreen mode

安装 Express

//install express
npm install express --save

Enter fullscreen mode Exit fullscreen mode

安装socket.IO

//install socket.io
npm install socket.io --save

Enter fullscreen mode Exit fullscreen mode

为了方便,安装 nodemon

//automatically restarts server upon detecting changes
npm install nodemon --save-dev

Enter fullscreen mode Exit fullscreen mode

目录结构

在主 chat_app 文件夹内(不在 node_modules 文件夹内):

  1. 创建公共文件夹并包括:
    • 索引.html
    • 样式.css
    • 聊天.js

[导航路径:/index.html、/style.css、/chat.js]

您的目录结构将如下所示:

chat_app
│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │






在index.js中创建服务器

在 index.js 中使用 express 创建 node.js 服务器

// require express first
var express = require("express");
//require socket.IO
var socket = require('socket.io')

//setting up the express app by invoking the express function
var app = express();

//now create a server
//When the server starts listening on port 4000 then fire a callbak function
// The callback function will console.log a string 
var server = app.listen(4000, function(){
 console.log("Listening to requests on port 4000");

});
// serve a static file to the browser 
app.use(express.static("public"));

//Socket setup
//passing var server to the socket function and assigning it to var io
//essentially now socket.IO will work on this server just created
var io = socket(server);

Enter fullscreen mode Exit fullscreen mode

设置index.html

在index.html中:

  • 包含对 socket.io 库的引用
  • 包含对包含客户端 socket.io 代码的 JavaScript 文件的引用
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Newbie Guide</title>
       <script src="/socket.io/socket.io.js"></script>
        <link href="/style.css" rel="stylesheet" />
    </head>
    <body>
        <h1>Socket.io</h1>
    <script src="/chat.js"></script>
    </body>
</html>

Enter fullscreen mode Exit fullscreen mode

测试您的服务器

在终端中,使用以下命令重新启动服务器:

//if using nodemon
nodemon 

//if using node
node index.js

Enter fullscreen mode Exit fullscreen mode

你应该在终端中看到一些 console.logged 的​​内容

[nodemon] 1.18.11
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
listening for requests on port 4000,

Enter fullscreen mode Exit fullscreen mode

在浏览器中访问http://localhost:4000/ ,
你应该会看到你的网页。现在你就可以开始使用 socket.IO 了!

建立第一个套接字连接

在 index.js 中

//declare var io which is a reference to a socket connection made on the server
var io= socket(server);

//Then use the io.on method which looks for a connection
//upon a connection execute a callback function which will console.log something
io.on('connection', function(){
  console.log('made socket connection');
});

Enter fullscreen mode Exit fullscreen mode

在 chat.js 中

//you already included a reference to the socket.io library in index.html so now you have access to it
//make a socket by declaring var socket which will make a socket connection to localhost:4000
var socket = io.connect("http://localhost:4000");
Enter fullscreen mode Exit fullscreen mode

在终端中:

nodemon

Enter fullscreen mode Exit fullscreen mode

然后在终端中检查 console.log 消息:

[nodemon] 1.18.11
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
listening for requests on port 4000,
made socket connection

Enter fullscreen mode Exit fullscreen mode

结论

现在,你已经可以在服务器和客户端上使用 socket.IO 来开发一些有趣的东西,比如聊天应用。更多内容请见第二部分。

资源

  1. https://socket.io/
  2. https://openclassrooms.com/en/courses/2504541-ultra-fast-applications-using-node-js/2505653-socket-io-let-s-go-to-real-time
  3. https://sabe.io/tutorials/how-to-build-real-time-chat-app-node-express-socket-io
  4. https://socket.io/docs/client-api/#socket-on-eventName-callback
  5. http://wern-ancheta.com/blog/2013/08/25/creating-a-real-time-chat-application-with-socket-dot-io/
  6. http://danielnill.com/nodejs-tutorial-with-socketio
文章来源:https://dev.to/kauresss/socket-io-guide-for-newbies-5hdm
PREV
如何使用 React.js 构建实时电影投票系统
NEXT
评论不是帖子