Reputation: 19
I have a database that I am hosting locally and need to be able to access it using Javascript for this website that I have https://nujabes.xyz/. For the server side of things, I am hosting it using Rust because that is what my database is written in:
TCP Server Rust
:
use std::{
io::Read,
net::{Shutdown::Both, TcpListener, TcpStream},
thread::spawn,
};
fn handle_client(mut stream: TcpStream) {
let mut data = [0 as u8; 50]; // using 50 byte buffer
while match stream.read(&mut data) {
Ok(_size) => {
//println!("{:?}", String::from_utf8(data[0..size].to_vec()));
// stream.write(&data[0..size]).unwrap();
true
}
Err(_) => {
println!(
"An error occurred, terminating connection with {}",
stream.peer_addr().unwrap()
);
stream.shutdown(Both).unwrap();
false
}
} {}
}
fn main() {
let address = "localhost";
let port = "80";
let listener = TcpListener::bind(format!("{}:{}", address, port)).unwrap();
println!("{}", format!("Server listening on port {}", port));
for stream in listener.incoming() {
match stream {
Ok(stream) => {
println!("New connection: {}", stream.peer_addr().unwrap());
spawn(move || {
handle_client(stream);
});
}
Err(e) => {
println!("Error: {}", e);
}
}
}
// close the socket server
drop(listener);
}
Client Side Javascript
:
function connect() {
let address = "localhost";
let port = "80";
console.log(`Attempting to connect to ${address} at ${port}...`);
let socket = new WebSocket(`wss://${address}:${port}`);
socket.onmessage = function(event) {
console.log(`Message :: ${event.data}`)
};
socket.onclose = function(event) {
console.log(`Closed :: ${event.code} :: ${event.reason}`);
};
socket.onerror = function(error) {
console.log(`Error :: ${error.message}`)
};
}
The output from the console after pressing the Login
or Register
button on the main page to cause it to attempt the connection is of the following:
Attempting to connect to localhost at 80... main.js:8:13
Firefox can’t establish a connection to the server at wss://localhost:80/. main.js:9:17
Error :: undefined main.js:20:17
Closed :: 1006 ::
There is also feedback on the server's side where it is actually recieving a connection:
Server listening on port 80
New connection: [::1]:64374
Why isn't the connection holding? What is up with this Firefox error?
Context: I have forwarded port 80
as well as a few other ports already.
Upvotes: 0
Views: 1405
Reputation: 8718
It seems like your server is trying to use regular TCP sockets while your client-side code is using WebSockets, which do make use of TCP sockets but layer a whole new protocol on top of that.
The connection does get established, but during the client-side's WebSocket handshake etc, it fails and therefore errors.
You're better off finding a Rust library that allows you to create a WebSocket server instead of a regular socket server. I don't think client-side JavaScript can even use regular sockets.
Upvotes: 5