0
我正在嘗試使用官方的socket.io教程,但無法讓服務器接收消息。我花了幾個小時嘗試各種各樣的事情。我完全沒有想法。Socket.io服務器不會收到消息
這裏的服務器:
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) {
//socket.emit('greeting', 'welcome to the chat');
socket.on('chat', function (msg) {
console.log('message: ' + msg);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
和客戶端:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</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>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
//localStorage.debug = '*';
var socket = io("http://localhost:3000/");
socket.on('greeting',
function (msg)
{
console.log(msg);
}
);
/*
$('form').submit(function()
{
socket.emit('chat message', $('#m').val());
//$('#m').val('');
return false;
});
*/
$("#sendBtn").click(function()
{
socket.emit('chat', $('#m').val());
return false;
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button id="sendBtn">Send</button>
</form>
</body>
</html>
客戶端可以從服務器接收郵件,但周圍的其他方法不起作用。我試着打開調試,但我不知道我看到的是對還是錯。但是,當我按網頁上的發送時,肯定會發生互動。
這裏是它的外觀從客戶端:
哇。我沒有看到!非常感謝Eduardo! –