gearDev
gearDev

Reputation: 39

Can I connect a websocket to a non websocket server

I have rust TCP server code:

fn main() {
    let mut server:  TcpListener = TcpListener::bind("0.0.0.0:8080")
        .expect("[SERVER]: Failed to bind");
    let mut handler: Handler     = Handler::new();
    
    loop {
        let mut Client = server.accept().unwrap();
        //Handler basically tests if client has send a message and prints that message out
        //the problem is, the client "Connects" server-side, but the websocket client say's it is "connecting"
        handler.newClient(Client.0);
    }

}

And I have websocket client code that connects to the server (from the browser):

let ws = new WebSocket("ws://0.0.0.0:8080");
ws.onopen = function(event) {
  ws.send("Hello, world!");
}

Anytime a client connects the server will create a new thread for it and log "Client connected" and also logs anything the client sends. When I execute the client script the server Prints out "Client connected" as expected. But it never gets "Hello, world!", which the client is supposed to send. I am suspecting its because you have to make a actual websocket server. Is there any way to connect a websocket to a non-websocket/socket.io server? Or at least use a different way to connect to a non socket.io/websocket server with js in the browser? Thanks!

Upvotes: 0

Views: 1755

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595320

A WebSocket connection involves an initial handshake before any data can be exchanged. That handshake requires the client to send an HTTP request asking for an upgrade to WebSocket, and the server to send back an HTTP response indicating whether that upgrade is successful or not. Only if successful can WebSocket messages than be exchanges back and forth.

Your example server is not implementing the WebSocket protocol, so the WebSocket client will not be able to complete that initial handshake, which is why you are not seeing any data arrive from ws.send(). The client will not fire the onopen event if the handshake fails. It will instead fire the onerror event, which your example is not handling.

So, to answer your questions:

  • there is no way for a WebSocket client to connect to a non-WebSocket server.

  • there is no standard API that will allow a browser to make a connection to a non-HTTP or non-WebSocket server 1. Typically, in the past, before the invention of WebSockets, that would be handled outside of the browser context using Java applets or ActiveX controls, but that kind of technology is no longer used in modern Web systems.

1: actually, Chrome and FireFox have extensions that allow for the use of raw TCP/UDP sockets, but other browsers do not. See Connecting to TCP Socket from browser using javascript. But these are based on deprecated technologies, so don't expect them to work reliably/at-all nowadays.

Upvotes: 4

Related Questions