最简单的 Socket.io 例子是什么?

所以,我最近一直在努力理解 Socket.io,但我并不是一个超级伟大的程序员,而且几乎我在网上找到的每一个例子(相信我,我已经找了很久很久) ,都有额外的东西让事情变得复杂。很多示例都会做一些让我感到困惑的事情,或者连接到一些奇怪的数据库,或者使用咖啡脚本或者大量的 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.

177997 次浏览

编辑: 我觉得对于任何人来说,最好在 Socket.IO 开始页面上查阅优秀的 聊天的例子。自从我提供了这个答案以来,这个 API 已经相当简化了。也就是说,这里是最初的答案更新小-小为新的 API。

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

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);

也许这也能帮到你。我无法理解 socket.io 是如何工作的,所以我尽可能地总结了一个例子。

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

首先,从一个空目录开始,创建一个名为 包裹 Json的非常简单的文件,在其中放入以下内容。

{
"dependencies": {}
}

接下来,在命令行上,使用 npm 安装本示例所需的依赖项

$ npm install --save express socket.io

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

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

创建一个名为 Server.js的文件,这显然将是我们的服务器由节点运行。输入以下代码:

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);

创建最后一个名为 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>

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

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

如果你打开一个网页浏览器,并指向你正在运行节点进程的主机名,你应该会看到同样的数字出现在你的浏览器中,连同任何其他连接的浏览器看着同一个页面。

这是我的投稿!

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

该代码显示了如何处理通过标记为//Mirror 的代码段从客户机反弹到服务器的 hello 消息的变量。

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

// 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);

我知道这个帖子已经有好几年历史了,但是有时候像我这样的有资格证书的新手需要一个完全精简到最简单形式的工作范例。

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

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

应用程序

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
});


});

.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>

跑步时间:

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

使用类似这样的 左舷测试来确保您的端口是开放的。

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

充其量,在使用 http.createServer 时,它为您修改了以下两行:

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

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

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

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);
});

以及用于运行应用程序的 运行这些命令

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

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

enter image description here