Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>iChat - Realtime Node Socket.io Chat App</title>
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="js/client.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav>
<img class="logo" src="chat-removebg-preview (1).png">
</nav>
<div class="container">
<div class="message right">Jack : Hi Peter </div>
<div class="message left"> Peter : Hi Jack ! how are you ?</div>
</div>
<div class="send">
<form action="#" id="send-container">
<input type="text" name="messageInp" id="messageInp">
<button class="btn" type="submit">Send</button>
</form>
</div>
</body>
</html>
字符串
index.js
const { Socket } = require('socket.io');
// Node server which will handle socket io connections
const io = require('socket.io')(8000)
const users = {};
io.on('connection', Socket => {
socket.on('new-user-joined', Name => {
console.log("New user", Name)
users[socket.id] = Name;
socket.broadcast.emit('user-joined', Name)
});
socket.on('send', message => {
socket.broadcast.emit('receive', { message: message, Name: users[socket.id] })
});
})
型
client.js
const socket = io('https://localhost:8000');
const form = document.getElementById('send-container');
const messageInput = document.getElementById('messageInp')
const messageContainer = document.querySelector(".container")
const Name = prompt("Enter your name to join")
socket.emit('new-user-joined', Name)
型
我是从一个教程聊天网站,然后我键入这个:
const Name = prompt ("Enter your name to join")
socket.emit ('new-user-joined', Name)
型
我期待我会在网站的提示区域输入任何东西的名称,它会显示在终端,但它显示在终端什么都没有,当我键入,我刷新了很多次,并使用nodemon也以确保我的代码更新
1条答案
按热度按时间ebdffaop1#
你需要一个http服务器。我没有看到你在你的代码中创建了一个http服务器。请检查官方文档。
你可以试试这个
index.js
字符串
client.js
型
这段代码将没有任何问题。