我正在尝试使用http://socket.io/get-started/chat/
中提供的示例来模拟聊天我拥有package.json文件中指定的所有依赖项,并且还使用npm安装相应的依赖项。
我的js文件包含以下代码:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req,res){
res.sendFile(__dirname+ '/chat.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
http.listen(8083, function(){
console.log("listening on port 8083");
});
我的HTML代码如下:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', 'Test');
$('#m').val('');
return false;
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
我能够连接到服务器。但是,当我在文本框中键入文本时,这不会反映在服务器中。我哪里错了?
答案 0 :(得分:1)
表单提交处理程序有问题。他们试图捕获表单提交事件,然后使用return false覆盖它,但表单仍然在提交,导致整个页面重新加载。
相反,我只是建议摆脱表单,只需使用按钮来触发发送。将onclick处理程序绑定到该元素,然后触发socket.emit方法:
<!-- include jQuery for convenience -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
var socket = io();
// add in document ready to only bind to the element once the page is done loading
$(document).ready(function() {
// use the click handler instead of form submit handler
$('#button').click(function(){
console.log('sending...')
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<!-- give the button element an id to bind to -->
<input id="m" autocomplete="off" /><button id="button">Send</button>
</form>
</body>
我还在jQuery中添加了,因为它看起来像是他们的演示所使用的,但他们并没有将它包含在HTML演示中。
有了这个,消息将进入服务器,但您仍然需要做一些工作才能让它发布回客户端。 Socket.IO网站上的其余教程可能会解决这个问题。