I have a Websocket program running on Ubuntu machine on Digital Ocean. The code is shortened below.
// server.ts
import ws from "ws";
const wss = new ws.Server({
port: 3002,
});
const handler = applyWSSHandler({ wss, router: appRouter, createContext });
console.log("WebSocket Server listening on ws://localhost:3002");
...
I host the server using nodemon server.ts or pm2 start server.ts. The program compiles and logs that Websocket Server is listening.
Now, here is a minimum code for a client which just checks if Websockets is active.
// client.js
const ws = new WebSocket('ws://xxx.xxx.xxx.xxx:3002'); // where xxx.xxx.xxx.xxx is the IPv4 of my Ubuntu machine
ws.onopen = function (event) {
console.log('connected');
};
Nothing gets logged, showing that the Websocket server isn't active.
I expect "connected" to be printed.
If I host my server locally instead of on Digital Ocean, and connect to "localhost:3002", "connected" does get printed out.
Is there something wrong with the way I am hosting the server, or am I connecting to the server wrongly?
Any help is appreciated. Thanks!
Related
I have a server and a client set up using the net module for Node.js.
Here is my server's code:
const server = net.createServer(function(socket) {
socket.on("data", function(data) {
// Do stuff with the connection
socket.end();
});
});
server.listen(this.port);
Here is my client's code:
const client = new net.Socket();
client.connect(this.port, this.host, function() {
client.write("Test Message");
});
When run on the same machine, both of these work fine, but when I try to connect from a different computer, the client hangs at client.connect() forever (until I terminate the process). When I tried to use the telnet command in command prompt, I don't get a response from the server, but the client doesn't just say connection refused. What's going on here?
The server app was running quite fine on Heroku but after migrating to Azure the server would not just start.
Here is the code..
const PORT = process.env.PORT || 2498;
const INDEX = '/index.html';
const server = express()
.use((req, res) => res.sendFile(INDEX, { root: __dirname }))
.listen(PORT, () => console.log(`We\'re live on channel : ${PORT}`));
const wss = new Server({ server });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('close', () => console.log('Client disconnected'));
ws.on('message', (message) =>{
// this stays within the server
console.log('[SERVER]: Received a message => %s', message );
})
})```
.........
Clients connected are returning not establish an handshake ....
Azure web app only supports the exposure of port 80 and 443 for website access.
My previous requirements and test results:
I think your problem is a typical problem. I also had related requirements before, and the test failed in the webapp. All documents of Azure app service, talking about websocket, all use SignalR. I also tested the signalr service and it was successful, but this service is free and currently only supports 20 client connections.
What I thought before was to create a console program and put it in webjob to let webjob provide websocket service, but it all failed in the end.
Because azure webapp runs in a sandbox environment, and only open ports 80 and 443, we can't do more configuration. Obviously, the port that your websocket service starts is 2498, so it is not supported.
Suggestion
If you must use websocket, regardless of programming language, you must support custom port opening, such as using Virtual Machine.
You can compare the charges of azure cloud service and virtaul machine. Which one is right for you and which one to use.
Another suggestion is that you can buy a third-party intranet penetration tool and use a fixed IP or URL, such as ngrok, so that you can put the websocket service on your company's internal server. (The test is valid).
Of these three options, intranet penetration may be the most cost-effective choice. You can choose according to your needs.
I am very new to web development, so any tips regarding the following matter will be useful!
So, the client written in javascript is supposed to communicate with the server written in python. I am trying to establish websocket connection between two PCs running UBUNTU and Windows OS
They work perfectly fine when I run them using UBUNTU, using localhost.
Also, everything works fine when the server is in UBUNTU and the client is in Windows.
Only when the server is located in Windows and the client is in UBUNTU I keep running into the same error.
'Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT.
I tried turning off the firewall settings in Windows, but it didn't work.
Any input will be very appreciated!
Python Server
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Javascript Client
var ws = new WebSocket("ws://localhost:1337/");
ws.onopen = function(){
console.log("Connection is Established");
ws.send("Message to Send");
};
ws.onmessage = function(evt) {
var received_msg = evt.data;
console.log(received_msg);
};
Okay, I found what was wrong.
Completely forgot that I had to change my router settings for port forwarding.
I'm trying to host a Websocket server on my heroku app. There already is a GraphQL server running, but I don't think it's the cause of my problem.
So my server is started like this
const wss = new ws.Server({ port: port }, () => console.log(`Serveur WebSocket prĂȘt ${port}`));
There is no error, but when I try to connect to the server in my browser, just like this :
const ws = new WebSocket('wss://ethyme-api.herokuapp.com/');
I get an error 404.
So my question is, what is the path of the ws server, so I can connect to it ?
Thanks
If your Heroku app is called ethyme-api and and your locally run application is available under ws://localhost:$PORT/ the websocket will be available under wss://ethyme-api.herokuapp.com/ and ws://ethyme-api.herokuapp.com/
I have a Java webapp and a browser application that connects to it over WebSockets like this in my client-side Javascript code:
function connect() {
var username = 'my-user';
var url = `ws://${document.location.host}${document.location.pathname}chat/${username}`;
log(`making WebSocket connection to ${url}`)
var ws = new WebSocket(url);
ws.onmessage = (event) => {
var message = JSON.parse(event.data);
log(message.message);
};
ws.onerror = (event) => {
log(event);
}
}
The endpoint when running Tomcat locally is ws://localhost:8080/my-app/chat/my-user
The endpoint when running Tomcat under Docker is ws://localhost:8090/my-app/chat/my-user (port 8090)
This works fine when connecting to my local Tomcat, but not when connecting to Docker Tomcat.
The error I get back when trying to connect to the Docker Tomcat is:
WebSocket connection to 'ws://localhost:8090/my-app/chat/my-user' failed: Error during WebSocket handshake: Unexpected response code: 404
Any ideas? From what I can tell, I don't need to open any additional ports in Docker (I have 8090 mapped properly). I don't know if there is any additional logging I can turn on in Tomcat to show me the endpoints. Maybe I just am not specifying the right endpoint?