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);
});
});
的index.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>
我进入终端屏幕的所有内容都是“用户连接”。或者&#39;用户断开连接&#39;每次我在localhost中输入一条消息。有谁知道我失败的地方?这些是我使用的两个节点索引文件,以使应用程序工作。 似乎每次按下它时我的发送按钮都刷新了页面,使得客户端连接起来了。消息触发器。
答案 0 :(得分:0)
确保阻止表格默认功能。
var socket = io();
$('form').submit(function(e){
e.preventDefault();
});
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});