Здравствуйте!
Похоже, что проблема с функцией звонка связана с дублированием метода initiateCall в вашем JavaScript-коде. Это вызывает бесконечную рекурсию, из-за которой вызов не инициируется. Давайте исправим эту проблему, переименовав один из методов, чтобы избежать конфликта имён.
Шаги по исправлению:
-
Переименуйте метод initiateCall(peerId) в startCall(peerId). Это позволит избежать конфликта с методом initiateCall(), который используется как обработчик события нажатия кнопки звонка.
-
Обновите вызовы метода везде, где используется initiateCall. Замените их на startCall там, где нужно инициировать звонок с определённым peerId.
-
Создайте отдельный обработчик для кнопки звонка, который будет вызывать startCall(remoteId).
Исправленный JavaScript-код:
Ниже приведён обновлённый JavaScript-код с внесёнными изменениями:
<!-- ... ваш HTML-код до конца остается без изменений ... -->
<script>
class P2PChat {
constructor() {
this.peer = null;
this.connections = new Map();
this.currentCall = null;
this.localStream = null;
this.activePeerId = null; // Активный Peer ID для чата
// Элементы интерфейса
this.peerIdDisplay = document.getElementById('peer-id');
this.connectBtn = document.getElementById('connect-btn');
this.remoteIdInput = document.getElementById('remote-id');
this.messagesArea = document.getElementById('messages');
this.sendBtn = document.getElementById('send-btn');
this.messageInput = document.getElementById('message-input');
this.onlineUsersList = document.getElementById('online-users');
this.fileInput = document.getElementById('file-input');
this.sendFileBtn = document.getElementById('send-file-btn');
this.callBtn = document.getElementById('call-btn');
this.activePeerDisplay = document.getElementById('active-peer');
// Элементы окна звонка
this.callWindow = document.getElementById('call-window');
this.callerIdSpan = document.getElementById('caller-id');
this.acceptCallBtn = document.getElementById('accept-call-btn');
this.rejectCallBtn = document.getElementById('reject-call-btn');
this.initPeer();
this.bindEvents();
}
initPeer() {
this.peer = new Peer();
this.peer.on('open', (id) => {
this.peerIdDisplay.textContent = id;
this.addOnlineUser(id, true); // Добавить себя в список онлайн пользователей
});
this.peer.on('connection', (conn) => this.handleConnection(conn));
this.peer.on('call', (call) => this.handleIncomingCall(call));
this.peer.on('error', (err) => {
console.error(err);
alert('Произошла ошибка: ' + err);
});
}
bindEvents() {
this.connectBtn.addEventListener('click', () => this.connectToPeer());
this.sendBtn.addEventListener('click', () => this.sendMessage());
this.messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.sendMessage();
});
this.sendFileBtn.addEventListener('click', () => this.sendFile());
this.callBtn.addEventListener('click', () => this.initiateCallButtonHandler());
// Обработчики для окна звонка
this.acceptCallBtn.addEventListener('click', () => this.acceptCall());
this.rejectCallBtn.addEventListener('click', () => this.rejectCall());
// Обработчик клика по пользователю для выбора активного чата
this.onlineUsersList.addEventListener('click', (e) => {
const li = e.target.closest('li');
if (li && !li.classList.contains('active')) {
this.selectActivePeer(li);
}
});
}
connectToPeer() {
const remoteId = this.remoteIdInput.value.trim();
if (!remoteId) {
alert('Введите Peer ID для подключения.');
return;
}
if (this.connections.has(remoteId)) {
alert('Уже подключены к этому Peer.');
return;
}
const conn = this.peer.connect(remoteId);
conn.on('open', () => {
this.setupConnection(conn);
this.addOnlineUser(remoteId);
this.appendSystemMessage(`Соединение с ${remoteId} установлено.`);
if (!this.activePeerId) {
this.setActivePeer(remoteId);
}
});
conn.on('error', (err) => {
console.error(`Ошибка соединения с ${remoteId}:`, err);
this.appendSystemMessage(`Ошибка соединения с ${remoteId}: ${err}`);
});
conn.on('close', () => {
this.appendSystemMessage(`Соединение с ${remoteId} закрыто.`);
this.removeOnlineUser(remoteId);
this.connections.delete(remoteId);
if (this.activePeerId === remoteId) {
this.activePeerId = null;
this.activePeerDisplay.textContent = 'Нет активного чата';
}
});
}
handleConnection(conn) {
if (this.connections.has(conn.peer)) {
console.warn(`Уже есть соединение с ${conn.peer}`);
conn.close();
return;
}
this.setupConnection(conn);
this.addOnlineUser(conn.peer);
this.appendSystemMessage(`Peer ${conn.peer} подключился.`);
if (!this.activePeerId) {
this.setActivePeer(conn.peer);
}
}
setupConnection(conn) {
this.connections.set(conn.peer, conn);
conn.on('data', (data) => this.handleIncomingData(data, conn.peer));
conn.on('close', () => {
this.appendSystemMessage(`Соединение с ${conn.peer} закрыто.`);
this.removeOnlineUser(conn.peer);
this.connections.delete(conn.peer);
if (this.activePeerId === conn.peer) {
this.activePeerId = null;
this.activePeerDisplay.textContent = 'Нет активного чата';
}
});
}
handleIncomingData(data, peerId) {
try {
const parsedData = JSON.parse(data);
switch (parsedData.type) {
case 'message':
this.displayMessage(parsedData.content, 'other');
break;
case 'file':
this.receiveFile(parsedData, peerId);
break;
default:
console.warn('Неизвестный тип сообщения:', parsedData.type);
}
} catch (error) {
console.error('Ошибка разбора данных:', error);
this.appendSystemMessage(`Получены некорректные данные от ${peerId}.`);
}
}
sendMessage() {
const message = this.messageInput.value.trim();
if (!message) return;
if (!this.activePeerId) {
alert('Выберите пользователя для отправки сообщения.');
return;
}
const conn = this.connections.get(this.activePeerId);
if (!conn || conn.open === false) {
alert('Нет открытого соединения для отправки сообщения.');
return;
}
const data = JSON.stringify({ type: 'message', content: message });
try {
conn.send(data);
this.displayMessage(message, 'self');
this.messageInput.value = '';
} catch (err) {
console.error('Ошибка отправки сообщения:', err);
this.appendSystemMessage(`Не удалось отправить сообщение пользователю ${this.activePeerId}.`);
}
}
displayMessage(message, type) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', type);
messageDiv.textContent = message;
this.messagesArea.appendChild(messageDiv);
this.scrollToBottom();
}
appendSystemMessage(message) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', 'system');
messageDiv.textContent = message;
this.messagesArea.appendChild(messageDiv);
this.scrollToBottom();
}
addOnlineUser(userId, isSelf = false) {
if ([...this.onlineUsersList.children].some(li => li.querySelector('.user-id').textContent === userId)) {
return;
}
const li = document.createElement('li');
const userInfo = document.createElement('div');
userInfo.classList.add('user-info');
const status = document.createElement('span');
status.classList.add('status');
status.style.backgroundColor = isSelf ? '#4CAF50' : '#4CAF50';
const userIdSpan = document.createElement('span');
userIdSpan.classList.add('user-id');
userIdSpan.textContent = userId;
userInfo.appendChild(status);
userInfo.appendChild(userIdSpan);
li.appendChild(userInfo);
if (!isSelf) {
const userActions = document.createElement('div');
userActions.classList.add('user-actions');
const callButton = document.createElement('button');
callButton.textContent = 'Позвонить';
callButton.onclick = (e) => {
e.stopPropagation(); // Предотвращает выбор пользователя при нажатии кнопки
this.startCall(userId); // Изменено на startCall
};
userActions.appendChild(callButton);
li.appendChild(userActions);
}
this.onlineUsersList.appendChild(li);
if (!isSelf) {
this.appendSystemMessage(`${userId} подключился.`);
}
}
removeOnlineUser(userId) {
[...this.onlineUsersList.children].forEach(li => {
if (li.querySelector('.user-id').textContent === userId) {
this.onlineUsersList.removeChild(li);
this.appendSystemMessage(`${userId} отключился.`);
}
});
}
setActivePeer(peerId) {
// Снять выделение с текущего активного пользователя
[...this.onlineUsersList.children].forEach(li => {
if (li.classList.contains('active')) {
li.classList.remove('active');
}
});
// Выбрать нового активного пользователя
const targetLi = [...this.onlineUsersList.children].find(li => li.querySelector('.user-id').textContent === peerId);
if (targetLi) {
targetLi.classList.add('active');
this.activePeerId = peerId;
this.activePeerDisplay.textContent = `Активный чат с: ${peerId}`;
this.clearMessages();
}
}
selectActivePeer(li) {
const peerId = li.querySelector('.user-id').textContent;
this.setActivePeer(peerId);
}
clearMessages() {
this.messagesArea.innerHTML = '';
}
sendFile() {
const file = this.fileInput.files[0];
if (!file) {
alert('Пожалуйста, выберите файл для отправки.');
return;
}
if (!this.activePeerId) {
alert('Выберите пользователя для отправки файла.');
return;
}
const conn = this.connections.get(this.activePeerId);
if (!conn || conn.open === false) {
alert('Нет открытого соединения для отправки файла.');
return;
}
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const uint8Array = Array.from(new Uint8Array(arrayBuffer));
const data = JSON.stringify({
type: 'file',
content: uint8Array,
fileName: file.name,
fileType: file.type
});
try {
conn.send(data);
this.appendSystemMessage(`Вы отправили файл: ${file.name} пользователю ${this.activePeerId}.`);
this.fileInput.value = '';
} catch (err) {
console.error('Ошибка отправки файла:', err);
this.appendSystemMessage(`Не удалось отправить файл пользователю ${this.activePeerId}.`);
}
};
reader.onerror = (error) => {
console.error('Ошибка чтения файла:', error);
alert('Не удалось прочитать файл.');
};
reader.readAsArrayBuffer(file);
}
receiveFile(data, peerId) {
const { content, fileName, fileType } = data;
if (!content || !fileName || !fileType) {
console.error('Получены неполные данные файла:', data);
this.appendSystemMessage(`Получены некорректные данные файла от ${peerId}.`);
return;
}
try {
const uint8Array = new Uint8Array(content);
const blob = new Blob([uint8Array], { type: fileType });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.href = url;
link.download = fileName;
link.textContent = `Скачать файл: ${fileName}`;
link.className = 'file-link';
link.style.color = '#0066cc';
link.style.textDecoration = 'none';
link.style.display = 'block';
link.style.marginTop = '5px';
link.target = '_blank';
const fileMessage = document.createElement('div');
fileMessage.classList.add('message', 'other');
fileMessage.innerHTML = `Друг отправил файл: ${fileName}`;
fileMessage.appendChild(link);
this.messagesArea.appendChild(fileMessage);
this.scrollToBottom();
} catch (err) {
console.error('Ошибка обработки полученного файла:', err);
this.appendSystemMessage(`Не удалось обработать файл от ${peerId}.`);
}
}
// Переименован метод initiateCall(peerId) в startCall(peerId)
startCall(peerId) {
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => {
this.localStream = stream;
const call = this.peer.call(peerId, stream);
this.setupCall(call);
this.appendSystemMessage(`Вы позвонили ${peerId}.`);
})
.catch(err => {
console.error('Ошибка доступа к микрофону:', err);
alert('Не удалось получить доступ к микрофону.');
});
}
handleIncomingCall(call) {
this.callWindow.classList.add('active');
this.callerIdSpan.textContent = call.peer;
this.acceptCallBtn.onclick = () => {
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(stream => {
this.localStream = stream;
call.answer(stream);
this.setupCall(call);
this.callWindow.classList.remove('active');
this.appendSystemMessage(`Вы приняли звонок от ${call.peer}.`);
})
.catch(err => {
console.error('Ошибка доступа к микрофону:', err);
alert('Не удалось получить доступ к микрофону.');
});
};
this.rejectCallBtn.onclick = () => {
call.close();
this.callWindow.classList.remove('active');
this.appendSystemMessage(`Вы отклонили звонок от ${call.peer}.`);
};
}
setupCall(call) {
if (this.currentCall) {
this.currentCall.close();
}
this.currentCall = call;
call.on('stream', (remoteStream) => {
const audio = document.createElement('audio');
audio.srcObject = remoteStream;
audio.autoplay = true;
audio.controls = true;
audio.classList.add('audio-chat');
this.messagesArea.appendChild(audio);
this.scrollToBottom();
});
call.on('close', () => {
this.appendSystemMessage('Звонок завершен.');
});
call.on('error', (err) => {
console.error('Ошибка звонка:', err);
this.appendSystemMessage('Произошла ошибка во время звонка.');
});
}
acceptCall() {
// Логика принятия звонка уже реализована в handleIncomingCall
}
rejectCall() {
// Логика отклонения звонка уже реализована в handleIncomingCall
}
// Исправлен обработчик кнопки звонка
initiateCallButtonHandler() {
const remoteId = this.remoteIdInput.value.trim();
if (!remoteId) {
alert('Введите Peer ID для звонка.');
return;
}
if (remoteId === this.peer.id) {
alert('Вы не можете звонить себе.');
return;
}
this.startCall(remoteId); // Вызываем метод startCall
}
scrollToBottom() {
this.messagesArea.scrollTop = this.messagesArea.scrollHeight;
}
}
document.addEventListener('DOMContentLoaded', () => {
new P2PChat();
});
</script>
</body>
</html>
Ключевые изменения:
-
Переименование метода initiateCall(peerId) в startCall(peerId):
- Это позволяет избежать конфликта имён и предотвращает рекурсию.
- Метод
startCall(peerId) отвечает непосредственно за инициирование звонка.
-
Обновление обработчиков вызовов:
- В методе
addOnlineUser заменён вызов this.initiateCall(userId) на this.startCall(userId).
- Создан новый метод
initiateCallButtonHandler, который вызывается при нажатии на кнопку звонка. Этот метод считывает remoteId и вызывает this.startCall(remoteId).
-
Обновление метода bindEvents:
- Обработчик событий для кнопки звонка теперь вызывает
this.initiateCallButtonHandler() вместо this.initiateCall().
Почему это работает:
-
Избежание рекурсии: Переименовав один из методов, мы предотвратили бесконечную рекурсию, которая мешала корректной работе функции звонка.
-
Чёткое разделение ответственностей:
startCall(peerId) отвечает за фактическое инициирование звонка.
initiateCallButtonHandler() отвечает за обработку события нажатия на кнопку звонка и за передачу правильного peerId в startCall.
Дополнительные рекомендации:
-
Проверка консоли браузера:
Убедитесь, что во время тестирования вашего приложения консоль разработчика не выводит ошибок. Это поможет быстро выявить и исправить возможные проблемы.
-
Права доступа к микрофону:
Убедитесь, что вашему приложению разрешён доступ к микрофону. В некоторых случаях браузер может блокировать доступ, если вы не используете HTTPS.
-
Тестирование с двумя разными Peer ID:
Чтобы убедиться в корректности работы звонков, протестируйте приложение с двумя разными Peer ID (например, с двух разных браузеров или устройств).
-
Обработка закрытий звонков:
Рассмотрите возможность добавления дополнительных уведомлений или логики при завершении звонка, чтобы пользователи всегда были в курсе состояния звонка.
После внесения указанных изменений ваша функция звонка должна начать работать корректно. Если проблема сохраняется, пожалуйста, предоставьте дополнительную информацию о возможных ошибках в консоли или поведении приложения, чтобы мы могли помочь более детально.
Примечание: Для полноценной работы P2P-приложений через PeerJS необходимо, чтобы оба пользователя были подключены к одному и тому же PeerJS серверу или настроили свой собственный сервер. Убедитесь, что настройки PeerJS сервера корректны и что оба пользователя могут установить соединение между собой.