Node.js on cloud 9连接问题

时间:2015-09-15 22:13:38

标签: javascript node.js server client cloud9-ide

我在云端9中使用Node.js,我似乎无法弄清楚如何将客户端连接到socket.io。我到处搜索,但我似乎无法找出问题所在。

node.js服务器文件:

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

var users;

app.get('/', function(req, res){
  res.sendfile('index.html', {root: __dirname});
});

var server = app.listen(process.env.PORT, process.env.IP);

console.log("Server listening on: "+process.env.PORT+" "+ process.env.IP);

server.on('connection', function(socket){
  socket.emit('welcome', {message : 'Welcome', id : socket.id});

  socket.on('client', function(data){
    console.log("Client response"+data);
  });

  socket.on('username', function(data){
    console.log('Username recieved: '+data['username']);
  });
});

客户端javascript代码:

    <script>
        var socket = io.connect("https://march-madness-rentarosatomi5201.c9.io");

        socket.on('welcome', function(data){
            alert(data.message+" "+data.id);
            socket.emit('client', {data: 'hello', id: data.id});
        });

        function send(){
            username = document.getElementById('username_box').value;

            alert(username);

            socket.emit('username', {username: username});
        }
    </script>

1 个答案:

答案 0 :(得分:0)

在客户端,您需要以下内容:

<script src="https://march-madness-rentarosatomi5201.c9.io/socket.io/socket.io.js"></script>
<script>
        var socket = io.connect("https://march-madness-rentarosatomi5201.c9.io");

...