0
聊天是使用來自socket.io庫的websockets在nodejs中編程的,我有一個也使用socket.io的websockets的客戶端,但我無法做出兩人一起工作。出於某種原因,客戶端不會將消息發送到服務器(我有一個console.log函數,它應該在接收到消息時寫入控制檯但不寫任何內容)。爲什麼我在使用websockets的nodejs中的簡單聊天不會發送消息
服務器的代碼是:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
以及客戶端是:
<!DOCTYPE html>
<html>
<head>
<style>
* { margin:0; padding:0; font-size:11px; font-family:arial; color:#444; }
body { padding:20px; }
#message-list { list-style-type:none; width:300px; height:300px; overflow:auto; border:1px solid #999; padding:20px; }
#message-list li { border-bottom:1px solid #ccc; padding-bottom:2px; margin-bottom:5px; }
code { font-family:courier; background:#eee; padding:2px 4px; }
</style>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
log('<span style="color:#888">Sending "' + message + '" to the server!</span>');
}
// Outputs to console and list
function log(message) {
var li = document.createElement('li');
li.innerHTML = message;
document.getElementById('message-list').appendChild(li);
}
// Create a socket instance
socket = new WebSocket('ws://localhost:8080');
// Open the socket
socket.onopen = function(event) {
console.log('Socket opened on client side',event);
// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
};
</script>
</head>
<body>
<p>Messages will appear below (and in the console).</p><br />
<ul id="message-list"></ul>
<ul style="margin:20px 0 0 20px;">
<li>Type <code>socket.disconnect()</code> to disconnect</li>
<li>Type <code>socket.connect()</code> to reconnect</li>
<li>Type <code>sendMessageToServer('Your Message')</code> to send a message to the server</li>
</ul>
</body>
</html>
你有任何想法有什麼不對嗎? 在此先感謝!
嘗試從'socket.on('chat message''改爲'socket.on('message'',please ..根據[docs](https://socket.io/docs/client-api/ #socket-send-args-ack):''socket.send' _發送一個'message' event._,所以你需要在服務器端聽一個正確的。 – FirstOne
另外,那個cdn壞了......也許你是隻是遵循過時的教程,請參考:[https://socket.io/get-started/chat/](https://socket.io/get-started/chat/) – FirstOne
我將「聊天消息」更改爲'消息',但仍然是相同的問題 –