gpt4 book ai didi

Javascript 聊天室 : How to establish who im sending a message to?

转载 作者:行者123 更新时间:2023-11-28 19:31:02 27 4
gpt4 key购买 nike

所以我有聊天室工作所以如果收件人是 All 或 ALL 它广播我有这个工作所以如果你的名字是'Sam'它发送它与“私有(private)消息:”文本我不知道如何检查用户名的花名册并将其私下发送给该用户..

我的代码是:

//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');

var async = require('async');
var socketio = require('socket.io');
var express = require('express');

//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);

router.use(express.static(path.resolve(__dirname, 'client')));
var messages = [];
var sockets = [];
var users = {};

io.on('connection', function (socket) {
messages.forEach(function (data) {
socket.emit('message', data);
});

sockets.push(socket);

socket.on('disconnect', function () {
sockets.splice(sockets.indexOf(socket), 1);
updateRoster();
});

// Message Received
socket.on('message', function (msg, recipient) {
var text = String(msg || '');

if (!text)
return;

messages.push(msg);

var messageType;

if (recipient != '' && recipient != ' ' && recipient != 'All' && recipient != 'all') {
messageType = "private";
} else {
messageType = "public";
}

socket.get('name', function (err, name) {
var data = {
messageType: messageType,
recipient: recipient,
name: name,
text: text
};

broadcastMessage('message', data);
messages.push(data);
});
});

socket.on('identify', function (name) {
socket.set('name', String(name || 'Anonymous'), function (err) {
updateRoster();
});
});
});

function updateRoster() {
async.map(
sockets,
function (socket, callback) {
socket.get('name', callback);
},
function (err, names) {
broadcast('roster', names);
}
);
}

function broadcastMessage(event, data) {
let counter = 0;
let senderSocket;
let recipientSocket;

if (data.messageType === "public"){
sockets.forEach(function (socket) {
socket.emit('message', data); // send msg to all users
});

} else {
sockets.forEach(function (socket) { //HELP
if (data.recipient === 'Sam')
socket.emit('message', );
/* var person = socket.get('name', callback);
if (data.recipient === person){ // if true, recipient exists
socket.emit('message', data);
counter++; // if counter === 0, no user with recipient name exists
recipientSocket = socket;
recipientSocket.emit('message', data);
// socket.emit('message', data); // send private msg to recipient
} */

//else if (data.name === socket.username){
// send msg to sender
//senderSocket = socket;
// senderSocket.emit(event, data);
//}

});
}

if (data.messageType === "private") {

//console.log("counter: " + counter);
//if (counter === 0){
// senderSocket.emit('userNotFound', data);
//} else {

//}
}
}


function broadcast(event, data) {
sockets.forEach(function (socket) {
socket.emit(event, data);
});
}

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});

我的 html 和 angular.js 看起来像:

<!doctype html>
<html lang="en" ng-app>
<head>
<img src="bermanology-logo.png" alt="Bermanology">
<title>Chat Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/bootstrap-responsive.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
body {
padding-top: 60px;
}
</style>
<script>
function ChatController($scope) {
var socket = io.connect();

$scope.messages = [];
$scope.roster = [];
$scope.name = '';
$scope.recipient = '';
$scope.text = '';
$scope.errorMessage = '';
$scope.usernameError = '';
$scope.nameIsUnique = false;



$scope.validateUserName = function(){
var counter = 0;
if ($scope.name != ''){
$scope.setName($scope.name);
for (var i = 0; i < $scope.roster.length; i++){
if ($scope.roster[i] === $scope.name){
counter++;
$scope.usernameError = "username already taken";
}
}
if (counter === 0){
$scope.nameIsUnique = true;
}
$scope.roster.push($scope.name);
socket.emit('identify', $scope.name);
}
}

socket.on('connect', function () {
$scope.setName();
});

socket.on('message', function (msgData) {
if (msgData.messageType == "private"){
msgData.text = "private message: " + msgData.text;
} else {
}
$scope.messages.push(msgData);
$scope.errorMessage = '';
$scope.$apply();
});

socket.on('userNotFound', function (data) {
console.log("user not found!");

$scope.errorMessage = "User '" + data.recipient + "' not found";
$scope.$apply();
});

socket.on('roster', function (names) {
$scope.roster = names;
$scope.$apply();
});

$scope.send = function send() {
socket.emit('message', $scope.text, $scope.recipient);
$scope.recipient = '';
$scope.text = '';
};

$scope.setName = function setName(name) {
socket.emit('identify', name);
};

}

</script>
</head>
<body>
<div class="container" ng-controller="ChatController">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="pull-right">
<a href="https://c9.io" class="brand">Cloud9 IDE</a>
</div>
</div>
</div>
<div class="page-header">
<h1>Chat Example</h1>
</div>
<div ng-show="!nameIsUnique">
<form ng-submit="validateUserName()">
<div class="span2" ng-bind="usernameError"></div>
<div class="span2"><input type="text" class="input-block-level" ng-model="name" placeholder="Your Name"></div>
<input type="submit" class="span2 btn btn-primary" value="Enter chat">
</form>
</div>

<div class="row" ng-show="nameIsUnique">
<div class="span3">
<ul class="nav nav-list well">
<li class="nav-header">Local Users</li>
<li ng-repeat="user in roster" ng-bind="user">
</li>
</ul>
</div>
<div class="span9">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th class="span2">User</th>
<th class="span2">Message To</th>
<th class="span7">Text</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="msg in messages">
<td class="span2" ng-bind="msg.name"></td>
<td class="span2" ng-bind="msg.recipient"></td>
<td class="span7" ng-bind="privateMsgInfo + msg.text"></td>
</tr>
</tbody>
</table>
<div class="row controls">
<form ng-submit="send()">
<div class="input-append span7">
<input type="text" class="span4" ng-model="recipient" placeholder="Recipient"><br>
<input type="text" class="span6" ng-model="text" placeholder="Message">
<input type="submit" class="span2 btn btn-primary" value="Send" ng-disabled="!text">
</div>
</form>
<div class="span6" ng-bind="errorMessage"></div>
</div>
</div>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/angular.min.js"></script>
</body>
</html>

请帮忙

最佳答案

代替

var sockets = [];

你应该使用

var sockets = {};

并映射用户名=>套接字,这样

sockets['fred'] 

将为您获取 fred 所在的套接字

关于Javascript 聊天室 : How to establish who im sending a message to?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030668/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com