我正在尝试使用socket.io + angular创建聊天室Web应用程序。socket.io - 无法将消息发送到套接字中的特定房间
我有一个特定的文本框,其中用户输入他想连接的房间的名称。然后,我试图将该用户连接到该特定房间并将其所有消息发送到该房间。但是,当我试图发送一个字符串进入聊天时,请求正在服务器端处理(控制台日志输出从服务器打印),而不是在控制器上socket.on('chat_message' ,函数(数据)...)方法不会打印它的控制台日志。
我做错了什么?
代码如下。还有更多的代码我不认为是必需的(角度相关的东西)。
预先感谢
视图
<form ng-submit="submit()">
<input autocomplete="off" ng-model="insertedText" type="text" />
<button type="button" ng-click="submit()">
Send
</button>
</form>
控制器
mymodule.controller("cntrlChat", ['$scope', 'myService',
function($scope, myService){
var socket = io();
$scope.messages = [];
$scope.room= myService.get();
socket.emit('room', $scope.room);
$scope.submit=function(){
socket.emit('chat_message',{ room: $scope.room, msg: $scope.user+": "+$scope.insertedText });
$scope.insertedText='';
return false;
}
socket.on('chat_message', function(data){
console.log('room-->'+data.room+' msg---->'+data.msg);
$scope.$apply(function() {
$scope.messages.push(data.msg);
});
});
}]);
服务器
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
io.emit('chat_message', "welcome");
socket.on('room', function(room) {
socket.join(room);
});
socket.on('chat_message', function(data){
console.log("room---->"+data.room, "msg---->"+data.msg);
io.sockets.in(data.room).emit('chat message',data.msg);
});
socket.on('disconnect', function(){
io.emit('chat message', "Bye");
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
你会需要更多的细节不是“它不工作”,如果你想一些帮助 – tommybananas
添加描述 – Matoy