我正在嘗試使用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