node.js 什么是最简单的 Socket.io 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9914816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:24:20  来源:igfitidea点击:

What is an example of the simplest possible Socket.io example?

node.jssocket.io

提问by Cocorico

So, I have been trying to understand Socket.io lately, but I am not a supergreat programmer, and almost every example I can find on the web (believe me I have looked for hours and hours), has extra stuff that complicates things. A lot of the examples do a bunch of things that confuse me, or connect to some weird database, or use coffeescript or tons of JS libraries that clutter things up.

所以,我最近一直在尝试了解 Socket.io,但我不是一个超级伟大的程序员,几乎我在网上能找到的每个例子(相信我我已经找了好几个小时),都有额外的东西使事情复杂化。很多例子做了很多让我困惑的事情,或者连接到一些奇怪的数据库,或者使用 coffeescript 或大量的 JS 库使事情变得混乱。

I'd love to see a basic, functioning example where the server just sends a message to the client every 10 seconds, saying what time it is, and the client writes that data to the page or throws up an alert, something very simple. Then I can figure things out from there, add stuff I need like db connections, etc. And yes I have checked the examples on the socket.io site and they don't work for me, and I don't understand what they do.

我很想看到一个基本的、功能正常的示例,其中服务器每 10 秒向客户端发送一条消息,说明现在几点,然后客户端将该数据写入页面或发出警报,这非常简单。然后我可以从那里弄清楚事情,添加我需要的东西,例如数据库连接等。是的,我已经检查了 socket.io 站点上的示例,但它们对我不起作用,我不明白它们是做什么的.

回答by Linus Gustav Larsson Thiel

Edit:I feel it's better for anyone to consult the excellent chat exampleon the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

编辑:我觉得任何人都可以参考Socket.IO 入门页面上的优秀聊天示例。自从我提供这个答案以来,API 已经非常简化。话虽如此,这是为较新的 API 更新的原始答案。

Just because I feel nice today:

只是因为我今天感觉很好:

index.html

索引.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

应用程序.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

回答by error

Here is my submission!

这是我的提交!

if you put this code into a file called hello.js and run it using node hello.js it should print out the message hello, it has been sent through 2 sockets.

如果将此代码放入名为 hello.js 的文件中并使用节点 hello.js 运行它,它应该打印出消息 hello,它已通过 2 个套接字发送。

The code shows how to handle the variables for a hello message bounced from the client to the server via the section of code labelled //Mirror.

该代码显示了如何通过标记为 //Mirror 的代码部分处理从客户端退回到服务器的 hello 消息的变量。

The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.

变量名在本地声明而不是全部在顶部声明,因为它们仅用于注释之间的每个部分。这些中的每一个都可以在一个单独的文件中并作为自己的节点运行。

// Server
var io1 = require('socket.io').listen(8321);

io1.on('connection', function(socket1) {
  socket1.on('bar', function(msg1) {
    console.log(msg1);
  });
});

// Mirror
var ioIn = require('socket.io').listen(8123);
var ioOut = require('socket.io-client');
var socketOut = ioOut.connect('http://localhost:8321');


ioIn.on('connection', function(socketIn) {
  socketIn.on('foo', function(msg) {
    socketOut.emit('bar', msg);
  });
});

// Client
var io2 = require('socket.io-client');
var socket2 = io2.connect('http://localhost:8123');

var msg2 = "hello";
socket2.emit('foo', msg2);

回答by ray_voelker

Maybe this may help you as well. I was having some trouble getting my head wrapped around how socket.io worked, so I tried to boil an example down as much as I could.

也许这也可以帮助你。我在理解 socket.io 的工作方式时遇到了一些麻烦,所以我尽可能地把一个例子简化了。

I adapted this example from the example posted here: http://socket.io/get-started/chat/

我从这里发布的示例中改编了这个示例:http: //socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.jsonPlace the following in it.

首先,从一个空目录开始,创建一个名为package.json的非常简单的文件,将以下内容放入其中。

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

接下来,在命令行上,使用 npm 安装我们这个例子需要的依赖项

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.jsonfile again.

这可能需要几分钟时间,具体取决于您的网络连接速度 / CPU / 等。要检查一切是否按计划进行,您可以再次查看package.json文件。

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

Create a file called server.jsThis will obviously be our server run by node. Place the following code into it:

创建一个名为server.js的文件, 这显然是我们由 node 运行的服务器。将以下代码放入其中:

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

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

Create the last file called index.htmland place the following code into it.

创建名为index.html的最后一个文件,并将以下代码放入其中。

<html>
<head></head>

<body>
  <div id="message"></div>

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

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

You can now test this very simple example and see some output similar to the following:

您现在可以测试这个非常简单的示例,并看到一些类似于以下内容的输出:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.

如果您打开 Web 浏览器,并将其指向运行节点进程的主机名,您应该会在浏览器中看到相同的数字,以及查看同一页面的任何其他已连接浏览器。

回答by edwardsmarkf

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

我意识到这篇文章已经有好几年了,但有时像我这样的认证新手需要一个完全简化为绝对最简单形式的工作示例。

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

我能找到的每个简单的 socket.io 示例都涉及 http.createServer()。但是如果您想在现有网页中包含一些 socket.io 魔法怎么办?这是我能想到的最简单和最小的例子。

this just returns a string passed from the console UPPERCASED.

这只是返回从控制台传递的字符串大写。

app.js

应用程序.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

索引.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

跑步:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port testto ensure your port is open.

使用类似这个端口测试的东西来确保你的端口是开放的。

now browse to http://localhost/index.htmland use your browser console to send messages back to the server.

现在浏览到http://localhost/index.html并使用您的浏览器控制台将消息发送回服务器。

at best guess, when using http.createServer, it changes the following two lines for you:

最好的猜测是,在使用 http.createServer 时,它会为您更改以下两行:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

我希望这个非常简单的例子可以让我的新手朋友们免于挣扎。请注意,我避免使用“保留字”查找用户定义的变量名称作为我的套接字定义。

回答by Vishal Thakur

index.html

索引.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; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        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));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>

index.js

索引.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

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

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

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

And run these commandsfor run the application.

运行这些命令来运行应用程序。

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node start

and open the URL:- http://127.0.0.1:3000/Port may be different. and you will see this OUTPUT

并打开 URL:-http://127.0.0.1:3000/端口可能不同。你会看到这个输出

enter image description here

在此处输入图片说明