Javascript NodeJS + socket.io:简单的客户端/服务器示例不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6411070/
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-08-23 21:36:44  来源:igfitidea点击:

NodeJS + socket.io: simple Client/Server example not working

javascriptnode.jscometsocket.io

提问by helix

I'm using NodeJS v0.4.8 and the latest Version of socket.io from

我正在使用 NodeJS v0.4.8 和最新版本的 socket.io

npm install socket.io

npm 安装 socket.io

on Ubuntu:

在 Ubuntu 上:

Linux mars 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux

Linux mars 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux

The following code unfortunately doesn't produce any output, wheter on client, nor on server side.

不幸的是,以下代码不会产生任何输出,无论是在客户端还是在服务器端。

Does anybody have a clue?

有人有线索吗?

SERVER-SIDE

服务器端

var http = require('http'),  
io = require('socket.io'),
fs = require('fs'),
sys = require('sys');

respcont = fs.readFileSync('testclient.js');

server = http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(respcont);
});
server.listen(8082);

var socket = io.listen(server); 
socket.on('connection', function(client){ 

    sys.puts("New client is here!");
    client.send("hello world");

    client.on('message', function(msg) { sys.puts("client has sent:"+msg); }) ;
    client.on('disconnect', function() { sys.puts("Client has disconnected"); }) ;
}); 

CLIENT-SIDE

客户端

<html>
<body>
<script type="text/javascript" src="http://localhost:8082/socket.io/socket.io.js"></script>
<script> 
    var socket = new io.Socket(null,{port:8082,rememberTransport:true,timeout:1500});
    socket.connect();
    socket.on('connect', function() { 
        console.log('connected to server'); 
        socket.send('Hi Server...'); 
    });

    socket.on('message', function() { 
        console.log('received a message!');
    });

    socket.on('disconnect', function() { 
        console.log('disconnected from server'); 
    });

</script> 
</body>
</html>

The output from NodeJS (NOT the sys.puts("...") calls) is:

NodeJS 的输出(不是 sys.puts("...") 调用)是:

info - socket.io started debug - served static /socket.io.js debug - client authorized info - handshake authorized info - handshaken b61a5c2751c1c8c8493db4b79d19e779

信息 - socket.io 开始调试 - 服务静态 /socket.io.js 调试 - 客户端授权信息 - 握手授权信息 - 握手 b61a5c2751c1c8c8493db4b79d19e779

采纳答案by Alfred

I also(like Derrish) like to use expressframework to simplify my work(AWESOME :)). You can download and extract this sample from http://dl.dropbox.com/u/314941/socketio.zip. I believe you don't even have to install these modules because I have bundled them locally(just run) thanks to npm :).

我也(像 Derrish)喜欢使用express框架来简化我的工作(真棒:))。您可以从http://dl.dropbox.com/u/314941/socketio.zip下载并提取此示例。我相信您甚至不必安装这些模块,因为我已经将它们捆绑在本地(只需运行),这要感谢 npm :)。

How to install:

如何安装:

alfred@alfred-laptop:~/tmp/socketio$ uname -a
Linux alfred-laptop 2.6.35-28-generic #50-Ubuntu SMP Fri Mar 18 19:00:26 UTC 2011 i686 GNU/Linux
alfred@alfred-laptop:~/tmp$ wget http://dl.dropbox.com/u/314941/socketio.zip
alfred@alfred-laptop:~/tmp$ unzip socketio.zip
alfred@alfred-laptop:~/tmp$ cd socketio/
alfred@alfred-laptop:~/tmp/socketio$ node -v
v0.4.7
alfred@alfred-laptop:~/tmp/socketio$ npm -v
1.0.6
alfred@alfred-laptop:~/tmp/socketio$ node app.js

The code:

编码:

app.js:

应用程序.js:

// npm install express
// npm install socket.io

var sys         = require('sys'),
        express = require('express'),
        app         = express.createServer('127.0.0.1'),
        io          = require('socket.io'); 

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
    res.send('Hello World');
});

app.listen(3000);

var socket = io.listen(app); 

socket.on('connection', function (client){ 
  // new client is here!
  setTimeout(function () {
        client.send('Waited two seconds!');
    }, 2000);

  client.on('message', function () {
  }) ;

  client.on('disconnect', function () {
  });
});

public/index.html:

公共/index.html:

<html>
<p id="text">socket.io</p>

<script src="socket.io/socket.io.js"></script> 
<script src="jquery-1.6.1.min.js"></script><!-- Downloaded Jquery -->

<script> 
    $(document).ready(function(){

        var socket  = new io.Socket(),
                text        = $('#text');

        socket.connect();

        socket.on('connect', function () {
            text.html('connected');
        });

        socket.on('message', function (msg) {
            text.html(msg);
        });

        socket.on('disconnect', function () {
            text.html('disconnected');
        });

    });
</script> 

Listing of my modules:

我的模块列表:

alfred@alfred-laptop:~/tmp/socketio$ npm ls
/home/alfred/tmp/socketio
├─┬ [email protected] 
│ ├── [email protected] 
│ ├── [email protected] 
│ └── [email protected] 
└── [email protected]

Installed modules(NOT necessary):

已安装的模块(不是必需的):

npm install express
npm install socket.io

Browser will display:

浏览器会显示:

  1. socket.ioon start, but probably you can't see this because it will be replaced with connected.
  2. connectedwhen the user connects to socket.io.
  3. After 2 seconds it will display Waited two seconds!image
  1. socket.io在开始时,但您可能看不到这一点,因为它将被替换为connected.
  2. connected当用户连接到 socket.io 时。
  3. 2秒后显示 Waited two seconds!图片

回答by sreekumar

Express 3.0 + Socket.io working example

Express 3.0 + Socket.io 工作示例

server ( app.js )

服务器 ( app.js )

var express = require('express');
    var app = express.createServer();
    var socket = require('socket.io');
    app.configure(function(){
        app.use(express.static(__dirname + '/'));
    });
    var server = app.listen(8081);
    var io = socket.listen(server);
    io.sockets.on('connection', function (socket) {
        console.log("connnect");
        socket.on('disconnect', function (socket) {
        console.log("disconnect");
     });
}); 

client ( index.html )

客户端( index.html )

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:8081');
</script>

you can fork the code using the link below https://github.com/sreekumar-kr/Expree3.0---Socket.IO

您可以使用以下链接分叉代码 https://github.com/sreekumar-kr/Expree3.0---Socket.IO

回答by Derrish Repchick

I took your example and dropped it in an a node app using express. Your HTML code was placed in a static HTML file under public. Your example worked fine. The code is shown below. I wanted to make sure both the socket.io script file and the HTML file were being served up properly.

我拿了你的例子并将它放到了一个使用 express 的节点应用程序中。您的 HTML 代码被放置在 public 下的静态 HTML 文件中。你的例子工作正常。代码如下所示。我想确保 socket.io 脚本文件和 HTML 文件都被正确提供。

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

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

if (!module.parent) {
  app.listen(9000);
  console.log("server started at %s", (new Date()).toUTCString());
  console.log("listening on port %d", app.address().port);
}


// socket.io 
var socket = io.listen(app); 
socket.on('connection', function(client){ 
    console.log("New client is here!");
    client.send("hello world");
    client.on('message', function(msg){ console.log("client has sent:"+msg); }) ;
    client.on('disconnect', function(){ console.log("Client has disconnected"); }) ;
    client.on('disconnect', function(){ }) 
 });