SocketCreates a raw TCP socket that can be used directly in the browser.
const socket = new puter.net.Socket(hostname, port);
hostname (String) (Required)
The hostname of the server to connect to. This can be an IP address or a domain name.
port (Number) (Required)
The port number to connect to on the server.
A Socket object.
socket.write(data)
Write data to the socket.
data (ArrayBuffer | Uint8Array | string) The data to write to the socket.socket.close()
Voluntarily close a TCP Socket.
socket.addListener(event, handler)
An alternative way to listen to socket events.
event (SocketEvent) The event name to listen for. One of: "open", "data", "drain", "close", "error".handler (Function) The callback function to invoke when the event occurs. The callback parameters depend on the event type (see Events).socket.off(event, handler)
Remove a handler added with socket.on() or socket.addListener().
event (SocketEvent) The event name the handler was added for. One of: "open", "data", "drain", "close", "error".handler (Function) The same function that was passed to socket.on() or socket.addListener().socket.on("open", callback)
Fired when the socket is initialized and ready to send data.
callback (Function) The callback to fire when the socket is open.socket.on("data", callback)
Fired when the remote server sends data over the created TCP Socket.
callback (Function) The callback to fire when data is received.buffer (Uint8Array) The data received from the socket.socket.on("close", callback)
Fired when the socket is closed.
callback (Function) The callback to fire when the socket is closed.hadError (boolean) Indicates whether the socket was closed due to an error. If true, there was an error.socket.on("drain", callback)
Fired right after the open event when data was written before the socket opened, once all of that data has been sent. Writes made after the socket opens aren't queued, so they don't fire this event.
callback (Function) The callback to fire when the data written before the socket opened has been sent.socket.on("error", callback)
Fired when the socket encounters an error. The close event is fired shortly after.
callback (Function) The callback to fire when an error occurs.error (Error) An Error object describing what went wrong. The human-readable reason is available on error.message.<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
const socket = new puter.net.Socket("example.com", 80);
socket.on("open", () => {
socket.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
})
const decoder = new TextDecoder();
socket.on("data", (data) => {
puter.print(decoder.decode(data), { code: true });
})
socket.on("error", (error) => {
puter.print("Socket errored with the following reason: ", error.message);
})
socket.on("close", (hadError)=> {
puter.print("Socket closed. Was there an error? ", hadError);
})
</script>
</body>
</html>