我正在尝试在node.js中构建我的第一个应用程序 - 聊天。我有一个问题,发送消息到相应的房间。 socket.room没有存储,我想这是因为我尝试每次都通过刷新页面加载视图,而不是通过Ajax。这段代码可以吗?
server.js
var express = require('express')
, http = require('http')
, app = express()
, server = http.createServer(app)
, io = require('socket.io').listen(server)
, path = require('path')
, jade = require('jade');
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {layout: false});
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
app.get('/', function(req, res) {
res.render('home.jade');
});
app.get("/rooms", function(req, res) {
res.render('rooms.jade');
});
app.get("/music", function(req, res) {
res.render('music.jade');
});
app.get("/art", function(req, res) {
res.render('art.jade');
});
io.sockets.on('connection', function(socket) {
socket.on('joinRoom', function(data) {
console.log(data + ' joined');
socket.room = data;
socket.join(data);
});
socket.on('message', function(data) {
io.sockets.in(socket.room).emit('sendMess', data.message);
})
});
server.listen(3000);
client.js
var socket = io.connect();
$(document).ready(function() {
$('.submit').on('click', function(e) {
e.preventDefault();
var user = $('.user').val();
$.ajax({
url: 'rooms'
}).done(function(data) {
$('body').html(data);
console.log(user);
})
})
$('#rooms').on('click', 'a', function() {
var $this = $(this),
room = $this.data('name');
joinRoom(room);
});
$('#conversation').find('.send').on('click', function() {
var txt = $(this).prev('.message').val();
console.log(txt);
socket.emit('message', {message: txt});
})
socket.on('sendMess', function(data) {
$('<p>' + data + '</p>').insertAfter($('#conversation'));
})
})
function joinRoom(data) {
socket.emit('joinRoom', data);
}
home.jade
include header.jade
body
div.container
header
h1 A Chat application
form(name="input", action="", method="post")
| Username:
input(type="text", name="user", class="user")
input(type="submit", value="Login", class="submit")
rooms.jade
include header.jade
body
div.container
header
h1 ROMS
div#rooms
h2 Join to room
a(data-name='music', href='music') Music
a(data-name='art', href='art') Art
音乐/ art.jade
include header.jade
body
div.container
header
h1 MUSIC ROOM
div#rooms
h2 Join to room
a(data-name='music', href='music') Music
a(data-name='art', href='art') Art
div#conversation
input(type="text", name="message", class="message")
button(class="send") Send
答案 0 :(得分:0)
设置socket.room
不会使其持久化,您必须自己存储(例如:在数据库中)