我正在尝试使用node js
和socket.io
在两个用户之间进行一对一聊天。我试图通过单击chatroom
find friend
来打开button
,并且在文本字段username
中输入了chatGroupName
。
单击按钮后,它将检查``用户''是否为``在线'',这是从``onlineusers''数组中获取的,然后我想显示两个``用户''消息私下显示的聊天窗口。对不起,代码混乱。
服务器端脚本-> app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
const io = require('socket.io').listen(server);
var bodyParser = require('body-parser');
var nsp = io.of('/my-namespace');
var PORT = 8000;
users = [];
connections = [];
onlineusers = [];
rooms = [];
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/chat', (req, res) => {
res.render("chat") //pick the index.ejs file
})
io.on('connection', (socket) => {
console.log('New user connected!')
// console.log(socket.client.id)
connections.push(socket);
console.log('Connected : %s sockets connected', connections.length)
//disconnect user
socket.on('disconnect', function (data) {
// if (!socket.username) return;
users.splice(users.indexOf(socket.username), 1);
// updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected : %s sockets connected', connections.length)
});
//////////////////////////////////////////////////////////////////////////
socket.on('find_friend',function(data){
for(var i = 1; i <= onlineusers.length; i++){
// console.log(onlineusers.length)
console.log( "onlineusers",onlineusers[i])
if(data == onlineusers[i] && i < onlineusers.length ){
// console.log(true)
socket.emit('chat',onlineusers[i]);
}
else {
console.log('user not online')
}
}
})
/////////////////////////////////////////////////////////////////////////////////
//new message
socket.on('new_message', (data) => {
io.sockets.emit('new_message', {
message: JSON.stringify(data),
username: socket.username
});
})
//broadcast message
socket.on("typing", (data) => {
socket.broadcast.emit('typing', {
username: socket.username
});
})
// new user
socket.on('new_user', (data, callback) => {
callback(true);
socket.username = data;
users.push({
id: socket.id,
username: socket.username
});
onlineusers.push(data);
//console.log(onlineusers)
updateUsernames();
})
//update user list function
function updateUsernames() {
io.sockets.emit('get_users', onlineusers);
}
//create a new room
socket.on('new_room', (data, callback) => {
callback(true);
rooms.push(data);
socket.join(data);
socket.emit("sucess","you join the room");
//console.log(users)
updateRoomNames();
})
//update user list function
function updateRoomNames() {
io.sockets.emit('get_room', rooms);
}
})
//server listen to the port
server.listen(PORT, function () {
console.log('server is connected to the port : ' + PORT)
})
客户端脚本-> chat.js
$(function () {
//make connection
console.log("hello")
var socket = io() //.connect('http://localhost:8000')
//buttons and inputs
var message = $("#message")
var username = $("#username")
var send_message = $("#send_message")
var login = $('#Login')
var chatroom = $("#chatroom")
var feedback = $("#feedback")
var userForm = $("#userForm")
var userFormArea = $("#userFormArea")
var messageArea = $("messageArea")
var users = $("#users")
var rooms = $('#myDropdown')
var chatGroupName = $("#chatGroupName")
var createChatGroup = $("#createChatGroup")
var joinChatGroup = $("#joinChatGroup")
var friendName = $('#friendName')
var upper_name = $('#upper_name')
//Emit message
send_message.click(function () {
socket.emit('new_message', {
message: message.val()
})
message.val(''); //empty the message variable
})
socket.emit('create', 'room1');
//new user
login.click(function () {
socket.emit('new_user', username.val(), function (data) {
console.log(data)
if (data) {
userFormArea.hide();
// console.log("hide userform")
document.getElementById('messageArea').style.display = "block";
// console.log('show message area')
}
})
username.val(''); //empty the message variable
})
//create chat group
createChatGroup.click(function () {
socket.emit('new_room', chatGroupName.val(), function (data) {
console.log(data)
if (data) {
document.getElementById('messageArea').style.display = "block";
// socket.emit('create', chatGroupName.val())
// console.log('show message area')
}
})
chatGroupName.val(''); //empty the message variable
})
joinChatGroup.click(function () {
document.getElementById("myDropdown").classList.toggle("show");
window.onclick = function (event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
})
//here is the problem code
///////////////////////////////////*TEST1* */
friendName.click(function () {
socket.emit('find_friend', chatGroupName.val())
})
//
socket.on('chat', (data) => {
console.log(data)
// document.getElementById('messageArea').style.display = "block";
if (data) {
var html = '<h1 class = "upper_name">' + data + '</h1>';
// socket.on(data).emit(document.getElementById('messageArea').style.display = "block");
upper_name.html(html);
document.getElementById('upper_name').style.display = "block";
}
})
//////////////////////////////////TEST 1 END///
// List of users
socket.on('get_users', function (data) {
var html = '';
for (i = 0; i < data.length; i++) {
html += '<li class = "list-group-item">' + data[i] + '</li>';
}
users.html(html);
})
//list of rooms
socket.on('get_room', function (data) {
var html = '';
for (i = 1; i <= data.length; i++) {
html += '<a class = "list-group-item">' + data[i] + '</a>';
}
rooms.html(html);
})
//Listen on new_message
socket.on("new_message", (data) => {
feedback.html('');
message.val('');
chatroom.append("<p class='message'>" + data.username + ": " + data.message + "</p>")
})
//Emit typing
message.bind("keypress", () => {
socket.emit('typing', username)
})
//Listen on typing
socket.on('typing', (data) => {
feedback.html("<p><i>" + data.username + " is typing a message..." + "</i></p>")
})
//socket.emit('login',{userId:'YourUserID'});
});
/************************************************************* */
我的html文件-> chat.ejs
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" const="text/html;charset=UTF-8" />
<link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="socket.io/socket.io.js"></script>
<title>Simple Chat App</title>
</head>
<body>
<header>
<h1>Super Chat</h1>
</header>
<div id="userFormArea" style="margin-top: 30px" ;>
<section>
<label class="vertical-align">Enter username</label>
<input id="username" class="vertical-align" type="text" />
<button id="Login" class="vertical-align" type="button">Login</button>
</section>
</div>
<div id="messageArea" style="display:none";>
<div class="split left">
<div id = "groupchat">
<input id="chatGroupName" class="dropbtn" type="text" placeholder="Find people,group name..." />
<button id="createChatGroup" class="dropbtn" type="button">Create group</button>
<button class="dropbtn" id = "friendName">Enter friend's name</button>
<div class = "dropdown"><button id="joinChatGroup" class="dropbtn" type="button">Join group</button></div>
<div id="myDropdown" class="dropdown-content">
<!-- <a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>-->
</div>
</div>
<div class="col-md-4"></div>
<div class="well">
<h3>Online Users</h3>
<!--<input id="chat_with" class="vertical-align" type="text" placeholder="Enter name to chat with..." />-->
<ul >
<li>
<a href = # class="list_group" id="users" ></a>
</li>
</ul>
</div>
</div>
<div class="split right">
<div id ="upper_name">
</div>
<div id = "chat">
<section id="chatroom">
<section id="feedback"></section>
</section>
<section id="input_zone">
<input id="message" class="vertical-align" type="text" />
<button id="send_message" class="vertical-align" type="button">Send</button>
</section>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="chat.js"></script>
</body>
</html>
由于我真的不知道我可能无法正确解释该问题(这可能会有所帮助:这可能会尝试实现像Skype这样的格式,当您单击在线用户时,聊天窗口会打开。)任何帮助将不胜感激。