【发布时间】:2017-03-12 13:21:57
【问题描述】:
Index.js:
ar app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('index.html', { root: __dirname });
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
索引.html:
<!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>
</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', $('#m').val());
$('#m').val('');
return false;
});
</script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
每次我在本地主机中键入消息时,我在终端屏幕上看到的只是“用户已连接”或“用户已断开连接”。有人知道我在哪里失败吗?这些是我用来使应用程序工作的两个节点索引文件。 似乎我的发送按钮每次按下它都会刷新页面,从而触发“客户端已连接”消息。
【问题讨论】:
-
听起来您的表单正在提交并因此重新加载页面。
-
每次我按发送,它就是这样!
-
一个快速而肮脏的解决方案是删除 ,并为指向函数的按钮的 onClick 事件分配一个侦听器来执行 socket.emit(...)