[英]Using socket.io in node.js with express to display connection message when user logs in
我正在嘗試在socket.io中編寫一個Web聊天客戶端,但是首先我需要讓我的服務器與本地主機上的網站進行通信。
我收到“正在監聽”消息,但是當我在新選項卡中打開localhost表示用戶已連接時,什么也沒有發生。 Apache服務器正在運行,這很明確,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服務器正在提供網頁)。 這應該會在服務器控制台中生成'a user connected'
消息,但它不會執行任何其他操作,因為您的網頁對socket.io不會執行任何其他操作。
此外,您的服務器代碼看起來很可疑。 我建議您直接從此處獲取Express 4示例: http : //socket.io/docs/#using-with-the-express-framework 。
我不明白為什么您提到Apache服務器,因為它通常不是Express / socket.io實現的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.