I have a java app that functions as a server, listening to some port using the java.net.DatagramSocket class. The server is able to receive packets from some other java clients. What I did not manage to do is have a javascript client to the server. I've tried sending messages as WebSocket client
const ws = new WebSocket("ws://localhost:9999");
ws.addEventListener("open", () => {
console.log("CONNECTED")
})
But I'm getting the following error in the browser console:
App.js:9 WebSocket connection to 'ws://localhost:9999/' failed:
I've also tried using net library to send message:
const net = require("net");
const options = {
post: 9999
};
const client = net.createConnection(options);
client.write("TEST")
But I'm getting the following error:
Uncaught TypeError: net.createConnection is not a function
Is there any other way to do this?
UDP (DatagramSocket) and WebSocket are totally different things. WebSocket is a protocol on top of HTTP which is on top of TCP.
In JavaScript running inside the browser you cannot send UDP packages.
You can write some kind of a proxy server, which can receive messages via WebSocket from your JavaScript program and send them via UDP to your server.
Or extend your server with a WebSocket interface.