我正在尝试在 socket.io 中编写一个网络聊天客户端,但首先我需要让我的服务器与本地主机上的网站进行通信。
我收到“正在监听”消息,但是当我在新选项卡中打开 localhost 并表示用户已连接时,没有任何反应。 Apache 服务器正在运行,express 也在运行,node.js 也在运行。
这是我的index.js,它提供了我的index.html:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');});
io.on('connection', function(socket){
console.log('a user connected');});
http.listen(3000, function(){
console.log('listening on *:3000');});
这是我的index.html:
<!DOCTYPE html PUBLIC>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Web chat practice</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; }
</style>
</head>
<body>
Here will be the web chat:
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.();
</script>
</body>
</html>
我还可以使用 MEAN 堆栈中的一些一般方向。
最佳答案
index.html 中的这行代码会产生错误:
var socket = io.();
代码应该是:
var socket = io();
这将连接到您的 Express 服务器/socket.io(如果该网页由该 Express 服务器提供服务)。这应该会在您的服务器控制台中生成“用户已连接”消息,但它不会执行任何其他操作,因为您的网页不会使用 socket.io 执行任何其他操作。
<小时/>此外,您的服务器代码看起来很可疑。我建议您直接从此处获取 Express 4 示例:http://socket.io/docs/#using-with-the-express-framework .
我不明白您为什么提到 Apache 服务器,因为它通常不是 Express/socket.io 实现的一部分。
关于javascript - 在node.js中使用socket.io和express在用户登录时显示连接消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444478/