[英]Node.js Server-Client communication
I have a discord bot and i want to make a website for the bot. 我有一个不和谐的机器人,我想为该机器人制作一个网站。 For example I want to get the discord server members and print out to the website in a header or something else. 例如,我想获取不和谐的服务器成员,并以页眉或其他内容打印到网站。 Or if a button on the page was clicked, then the bot send a message to a channel. 或者,如果单击了页面上的按钮,则漫游器会将消息发送到频道。 Can you please tell me how can i do that? 你能告诉我我该怎么做吗?
You have to install a node package called Express using a command: npm install --save express . 您必须使用以下命令安装名为Express的节点软件包:npm install --save express。 you have to do: 你必须做:
var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));//name of the website folder that has the html and js files.
that will host a server on localhost:3000. 将在localhost:3000上托管服务器。 Then you will need to run the code on the node js server when a button is clicked like you said. 然后,当像您说的那样单击按钮时,您将需要在节点js服务器上运行代码。 For that you'll need to use sockets. 为此,您需要使用套接字。 You need another node package called socket.io. 您需要另一个名为socket.io的节点程序包。 so just run npm install --save socket.io 所以只需运行npm install --save socket.io
and then write down 然后写下来
var socket = require('socket.io')
var io = socket(server);
io.sockets.on("connection", function(Socket){
console.log("new connection " + Socket.id);
Socket.on("sendMessage", function(data){
//send a discord message.
});
});
Alright now on to the client. 好了,现在到客户那里。
In the HTML file you need to reference the socket library. 在HTML文件中,您需要引用套接字库。
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.dev.js"></script>
In the js file you need to write this. 在js文件中,您需要编写此代码。
var socket;
socket = io.connect("http://localhost:3000");
var button = document.getElementById('button');
button.addEventListener('click', function(){
var data = {};
socket.emit("sendMessage", data);
});
That will send a request to the server and when the server receives it it will run the code you typed in: 这将向服务器发送一个请求,当服务器收到请求时,它将运行您键入的代码:
Socket.on("sendMessage")
the website url is on localhost:3000. 网站网址位于localhost:3000上。 and its only availabe on you PC, its different to make it public. 并且它仅在您的PC上可用,并且与众不同。
I hope this helped ya! 希望这对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.