Explain Codes LogoExplain Codes Logo

Connecting to TCP Socket from browser using javascript

javascript
websockets
tcp-sockets
chrome-api
Alex KataevbyAlex Kataev·Jul 22, 2024
TLDR

To tap into a TCP socket from your browser, you utilize WebSockets which bridges the gap imposed by browser restrictions against direct TCP/IP socket communication. Here's a JavaScript snippet to roll out a WebSocket connection:

// Create WebSocket connection. Like calling up an old friend! var socket = new WebSocket('ws://example.com/socket'); // Once connected, send the greeting. Who starts a conversation without saying Hi? socket.onopen = () => socket.send('Hello Server!'); // An incoming message is like receiving a postcard. Let's see what it says: socket.onmessage = event => console.log('Server:', event.data); // Want to say something? Here's how you broadcast your thoughts: const sendMsg = msg => socket.send(msg); // Remember to hang up when you're done. Saving Server's tears for another day. const closeSocket = () => socket.close();

Replace ws://example.com/socket with the URL of your WebSocket server, and make sure your server is set up to interpret WebSocket messages as TCP socket communications.

Making WebSockets Work

Got no support for WebSockets from the existing TCP server? You could use a proxy server like the WS2S project to interpret WebSocket messages to TCP socket communication. It's like hiring a translator for a foreign diplomat.

Chrome and TCP Sockets

Few Chrome Apps, while still experimental, had tasted the power of raw TCP/UDP sockets through the Chrome API. However, as is the fate of all experimental things, Chrome Apps are now deprecated.

More Ways to Connect

With roadblocks everywhere, creativity comes to the rescue. Unveiling winner alternatives:

  • WebRTC: The new kid on the block for peer-to-peer communication.
  • jSocket: Uses Flash, an older technology soon to be phased out, like dinosaurs.
  • Server-side WebSockets: Create a WebSocket server (like with Node.js) acting as a translator for your client-side browser connections and native TCP sockets.

Future: Raw Socket Access?

As of now, no out-of-box TCP/IP socket connection exists for standard web browsers. Yet, hope isn't lost — drafts like W3C's Raw Sockets API hint towards more capable browsers in the future.

Exploring Examples and Patterns

Learning by doing works. Soak knowledge from HTML5 WebSocket examples, or explore the Chrome Sockets API (for Chrome extension developers). The ws2s GitHub repo is another treasure trove to learn browser-TCP socket connections.