Node.js net.Socket().connect() hangs and doesn't connect to server - javascript

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?

Related

How do I connect to Websockets program running on my server?

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!

Failed to load resource: the server responded with a status of 404 (Not Found) Node.js socket.io

I'm trying to create a server using Node.js and socket.io and it starts perfectly. However, when I'm trying to visit the site of my server through the browser, he writes "Cannot Get /" and in the console gives an error "Failed to Load Resource: The Server Respondd with A Status of 404 (Not Found)". For two days I'm trying to understand where the problem and I will be very grateful to your help. Here is my server code:
const express = require("express");
var http = require("http");
const app = express();
const port = process.env.PORT || 5000;
var server = http.createServer(app);
var io = require("socket.io").listen(server);
//middlewre
app.use(express.json());
io.on("connection", (socket) => {
console.log("connected");
console.log(socket.id, "has joined");
socket.on("/test", (msg) => {
console.log(msg);
})
});
server.listen(port, "0.0.0.0", () => {
console.log("server started");
});
Your server is currently not set up to handle any other http traffic than Websocket connection upgrade requests, which you can not make by entering a url in your browser. Also, the browser is not equipped to negotiate this connection upgrade or to keep the Websocket connection working once established. For this you need some javascript code to run on the client side.
The socket.io library provides everything you need, look at a minimally working example at the link provided below. You should basically just set up your server to serve an html document which provides a context from which the whole websocket connection upgrade can be managed - and the connection maintained - by the socket.io library.
https://socket.io/docs/v2#Minimal-working-example

Websocket between python server and javascript client

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.

Tomcat in Docker with webapp: Error during WebSocket handshake

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?

Nodejs - Connecting to mongodb database within a js file?

So i have been looking at how to use mongodb from this tutorial: http://doduck.com/node-js-mongodb-hello-world-example/
I have installed mongodb locally within my project folder that contains my html css and js, i run npm list mongodb within the project folder and i get the mongodb version. I haven't installed it globablly, but as far as i know that is ok right?
Anyways, i tried adding the example from the tutorial to test connect to a mongodb database. I just created a function and called it as soon as my page loads:
function connectMongo(){
alert("test1");
var MongoClient = require('mongodb').MongoClient;
alert("test2");
var myCollection;
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err){
throw err;
alert("mongoerror");
}
alert("connected to the mongoDB !");
// myCollection = db.collection('test_collection');
});
}
The first test alert works, but the second test does not appear. However, the rest of the code on the page still runs, so i dont think there is a syntax error. I have no idea how exactly im meant to run this example, can anyone tell me why my function is exiting after the line
var MongoClient = require('mongodb').MongoClient;
I also have mongoose installed, even though im not quite sure if im even using it in my example here
Sorry if my question is kind of vague, i have honestly no idea what im doing here
First although Nodejs is written in Javascript, you must clearly distinguish between client and server functions. Javascript's alert() is useful to pop messages on your browser. This is isn't something Nodejs does as it is a server app.
Forget about alert("message"); You want to use console.log("message"); to view log info on the server console.
Prerequisite
Let's quickly review Client-Server web interactions:
Server is up and running
Client Requests page via browser
Page shows up on the client's browser
Step 1
The missing step for you is (1), because the server is not up and running.
This is done by typing the following on your terminal:
$ node name_of_file_here.js
If there are errors in your syntax, or missing dependencies the console will log the errors. If none appear all should be well.
Step 2
Now at this point, you still can't expect to see anything "relevant" on the browser, because your server although it has setup a MongoDB instance, is still not listening to requests from clients.
Some code needs to be added:
'use strict';
var http = require('http');
var PORT=8009;
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
var d = MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
//Create a server
var server = http.createServer(function(request, response) {
console.log("received request");
// use MongoClient to get relevant data
// var relevant_data = ...;
// response.write(relevant_data);
response.write("hey there");
response.end();
});
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
Final Note
I am in no way a MongoDB guru, but I believe a mongodb service (server) has to be running on your system for the MongoDB client to be able to create a connection.
It sounds like you are trying to run the mongo connection javascript in the browser. The mongodb connection runs on the server via the node executable. So this is javascript code in the web app running server side, rather than javascript delivered by the web app to a browser to run client side.
Create a file test.js
function connectMongo(){
var MongoClient = require('mongodb').MongoClient;
console.log('MongoClient is',typeof MongoClient)
var myCollection;
var url = 'mongodb://127.0.0.1:27017/test';
var db = MongoClient.connect(url, function(err, db) {
if(err){
console.log("mongoerror", err);
throw err;
}
console.log("connected to the mongoDB!");
myCollection = db.collection('test_collection');
});
}
connectMongo()
Then on your system, at a command or shell prompt, run
node test.js
It should print
$ node test.js
MongoClient is function
connected to the mongoDB!
^C
Once your server is connected to the database you can pass messages from your front end javascript to the backend server code. Normally this is done via an Ajax http request, so your javascript makes additional HTTP requests in the background. The JQuery client side library provides a simple cross browser API for this. You could also use Websockets to pass message back and forth from the server via SocketIO
For the basics of a Node/Express/MongoDB app try this: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

Categories

Resources