英文:
Cant connect to websocket server
问题
在我的主机中创建了一个WebSocket服务器,地址为<www.example.com>,但客户端无法连接。以下是代码:
Server.js:
const ws = require('ws');
const wss = new ws.Server({ noServer: true });
const http = require('http');
const express = require('express');
const app = express();
app.get("/multiplayerChat2/", (req, res) => {
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
});
http.createServer(app).listen(8080); // 使用8080端口
function onSocketConnect(ws) {
console.log("hello");
ws.on('message', function (message) {
message = message.slice(0, 50); // 最大消息长度为50
wss.clients.forEach(function (client) {
client.send(message.toString("utf8"));
});
});
}
Client.js:
let socket = new WebSocket("wss://www.example.com/multiplayerChat2/");
socket.onerror = (err) => {
console.log("websocket error: ", err);
};
// 从表单发送消息
document.forms.publish.onsubmit = function () {
let outgoingMessage = this.message.value;
socket.send(outgoingMessage);
return false;
};
// 接收到消息 - 在div#messages中显示消息
socket.onmessage = function (event) {
let message = event.data;
let messageElem = document.createElement('div');
messageElem.textContent = message;
document.getElementById('messages').prepend(messageElem);
};
Client.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="publish">
<input type="text" id="message">
<input type="submit" value="Send">
</form>
<div id="messages"></div>
</body>
<script src="index.js"></script>
</html>
请注意,server.js文件位于<example.com/multiplayerChat2>。我在WebSocket连接URL上进行了一些更改,但WebSocket连接出现以下错误:
WebSocket connection to 'wss://www.example.com/multiplayerChat2/' failed:
编辑:好的,我认为这有点困难,但至少告诉我如何创建一个WebSocket服务器而不处理HTTP请求,但其来源在网站中。
编辑2:我稍微修改了代码并使用了process.env.PORT,但它说端口已被使用(因为它是网站的端口)。我在某处看到HTTPS的合法端口是443,HTTP的合法端口是80,但由于此错误,我无法使用8080、80或443。
英文:
I made a websocket server in my host in <www.example.com> but the client doesnt connect to it.
Here is the code :
Server.js :
const ws = new require('ws');
const wss = new ws.Server({noServer: true});
const http = require('http');
const express = require("express");
const app = express();
app.get("/multiplayerChat2/",(req,res) => {
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onSocketConnect);
});
http.createServer(app).listen();
function onSocketConnect(ws){
console.log("hello")
ws.on('message', function(message) {
message = message.slice(0, 50); // max message length will be 50
wss.clients.forEach(function(client){
client.send(message.toString("utf8"));
})
});
}
Client js :
let socket = new WebSocket("wss://example.com/multiplayerChat2/");
socket.onerror = (err) => {
console.log("websocket error : ",err);
}
// send message from the form
document.forms.publish.onsubmit = function() {
let outgoingMessage = this.message.value;
socket.send(outgoingMessage);
return false;
};
// message received - show the message in div#messages
socket.onmessage = function(event) {
let message = event.data;
let messageElem = document.createElement('div');
messageElem.textContent = message;
document.getElementById('messages').prepend(messageElem);
}
Client html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form name="publish">
<input type="text" id="message">
<input type="submit" value="Send">
</form>
<div id="messages"></div>
</body>
<script src="index.js"></script>
</html>
Note that the server.js file is in <example.com/multiplayerChat2>.
I made some changes on the websocket connection url but websocket connection gives this error :
WebSocket connection to 'wss://example.com/multiplayerChat2/' failed:
EDIT : ok i think this is a little bit hard but at least say how can i make a websocket server without handling http requests but its origin be in the website
EDIT 2 : I changed my code a little and i used process.env.PORT but it says the port is already used(because its the port of the website) i saw somewhere that the legal port for https is 443 and for http is 80 but i couldnt use 8080 or 80 or 443 due to this error
答案1
得分: 0
你不能打开 `http` 服务器并连接到 `wss://`。 必须使用 `https`,并指定证书的绝对路径。
```js
var server
var is_ssl = true;
if (is_ssl) {
var httpsOptions = {
key: fs.readFileSync(process.env.SSL_KEY_FILE),
cert: fs.readFileSync(process.env.SSL_CERT_FILE)
};
server = require('https').createServer(httpsOptions, app);
} else {
server = require('http').createServer(app);
}
英文:
you can't open http
server and connect with wss://
. it needs to be https
with specifying the absolute path of the certificate.
var server
var is_ssl = true;
if (is_ssl) {
var httpsOptions = {
key: fs.readFileSync(process.env.SSL_KEY_FILE),
cert: fs.readFileSync(process.env.SSL_CERT_FILE)
};
server = require('https').createServer(httpsOptions, app);
} else {
server = require('http').createServer(app);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论