我正在尝试创建一个具有嵌入式聊天功能的Node.js应用。我正在使用socket.io来创建聊天。我试图设置我的服务器/客户端,但客户端似乎没有连接。我的应用程序在套接字连接和断开时设置日志但它似乎永远不会记录任何东西。我认为客户端被阻止了,所以我打开了Chrome devtools,输入了:
var socket = io();
奇怪的是,我开始看到一串看似如下的失败请求:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1434334401655-37 404 (Not Found)
所以现在我确定它是我的服务器。这是我的服务器代码:
var express = require("express");
var mongoose = require("mongoose");
var io = require("socket.io").listen(app);
// var restAPI = require("./api");
// Set up the application.
var app = express();
app.use(express.static("static"));
// Mount up the rest API
// app.use("/rest", restAPI);
// Default index route.
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
// This will maintian a transcript of the chat
var transcript = []
// This route will return the transcript data as json
app.get("/transcript", function(req, res) {
res.json(JSON.stringify(transcript));
});
// Simple socket.io for chat application
// Lets keep a reference to how many connections we have
var count = 0;
io.sockets.on("connection", function(socket) {
// Increment the number of clients
count++
// Keep a reference to the socket
var current = socket;
// Log the connection
console.log("Connected to: " + current + " at " + Date.now() + ".");
// Log the current number of users
console.log("There are now " + count + "users connected.");
// Handle disconnection
socket.on("disconnect", function() {
// Same routine as connect
console.log(current + ": disconnected at " + Date.now() + ".");
console.log("There are now " + count + "users connected.");
});
});
app.listen(3000);
这是我的HTML客户端:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport">
<title>Paint</title>
<!-- <script src="/js/application.js"></script> -->
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
</head>
<body>
<header></header>
<nav></nav>
<aside>
<div id="toolbox"></div>
<!-- display: none; by default -->
<div id="chat"></div>
<div class="buttons">
<div class="toolBoxButton">Toolbox</div>
<div class="chatButton">Chat</div>
</div>
</aside>
<section></section>
<footer></footer>
<script>
var socket = io();
</script>
</body>
</html>
为什么客户端无法连接?
答案 0 :(得分:1)
我不知道这是否是唯一的问题,但你称之为:
var io = require("socket.io").listen(app);
在分配app
变量之前,它是undefined
。
此网址的请求:
http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1434334401655-37
是socket.io连接如何启动,这是正常的。问题是socket.io监听器在服务器上运行不正常,因此没有任何东西在监听该路由。
另外,我不知道是否:
io.sockets.on("connection", function(socket) {...});
适用于socket.io v1 +。 socket.io doc说使用它:
io.on('connection', function(socket) {...});