【发布时间】:2016-10-27 00:19:23
【问题描述】:
我正在学习 nodejs 使用 socket.io 的事件驱动编程,以便我可以构建一个聊天应用程序。
所以,我创建了一个Server 和Client,现在在localhost 中运行在不同的端口。
8080 的服务器
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http, {origins: '*.*', transports: ['websocket', 'xhr-polling']});
var port = process.env.PORT || 8080;
http.listen(port, function () {
console.log('Cat Server listening at http://127.0.0.1:%d', port);
});
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
console.log('Connection to client established ', socket);
var addedUser = false;
// when the client emits 'love event', this listens and executes
socket.on('LoveEvent', function (data) {
console.log("we tell the client to execute 'logevent'")
socket.broadcast.emit('LoveEvent', {
username: socket.username,
message: data
});
});
);
客户在 3000
客户端通过socket.io连接到服务器8080
我在public/chat.js 中有以下代码,它包含在public/index.html 中
var socket = io();
socket.connect('http://localhost:8080', {transports: ['websocket', 'xhr-polling']})
console.log("Connection to Cat socket server, ", socket)
而且,public/index.html 是
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="/chat.js"></script>
客户端结构是
$ ll
total 24
-rw-r--r-- 1 prayagupd staff 30 Nov 1 20:18 README.md
-rw-r--r-- 1 prayagupd staff 325 Nov 1 20:18 Server.js
drwxr-xr-x 91 prayagupd staff 3094 Oct 26 18:11 node_modules
-rw-r--r-- 1 prayagupd staff 249 Nov 1 20:18 package.json
drwxr-xr-x 8 prayagupd staff 272 Nov 1 20:22 public
node_modulessocket.js
$ ll node_modules/socket.io/lib/
total 80
-rw-r--r-- 1 prayagupd staff 5411 Oct 26 15:59 client.js
-rw-r--r-- 1 prayagupd staff 8933 Oct 26 15:59 index.js
-rw-r--r-- 1 prayagupd staff 5366 Oct 26 15:59 namespace.js
-rw-r--r-- 1 prayagupd staff 9493 Oct 26 15:59 socket.js
但是
当我启动我的服务器时
$ node Server.js
Cat Server listening at http://127.0.0.1:8080
和客户,
$ node Client.js
Cat client running at localhost:3000
我希望在服务器端收到一条连接消息,因为我正在使用 Server.js 中的消息作为 console.log('Connection to client established ', socket); 进行调试
我手动尝试从 chorme 控制台创建 socket 并发送了一个事件,服务器似乎没有订阅它。
s.connect("http://localhost:8080", {autoConnect : true})
Socket {io: Manager, nsp: "/", json: Socket, ids: 0, acks: Object…}
s.emit("LoveEvent", "Love")
Socket {io: Manager, nsp: "/", json: Socket, ids: 0, acks: Object…}
此外,当客户端在浏览器中时,在浏览器控制台中的transport=polling 上有以下404 error,
我不知道它为什么在 3000 端口上轮询,它本身就是。
当一切都在同一台服务器上时,它运行良好。我重构了它,现在:(
我这里有后端和前端代码 => prayagupd/lovejs
【问题讨论】:
标签: node.js websocket socket.io