codefrau / SqueakJS

A Squeak Smalltalk VM in Javascript
https://squeak.js.org
MIT License
365 stars 75 forks source link

Add WebSocket support #89

Closed ErikOnBike closed 4 years ago

ErikOnBike commented 4 years ago

This update allows WebSockets to be used from within the Smalltalk image. It is tested on Cuis and Squeak using the following code [*]:

| ws |
ws := WebClient webSocket07: 'https://echo.websocket.org/' protocol: nil.
ws onMessage: [ :message | Transcript show: message; cr ].
ws fork.
ws send: 'This is the first message'.
ws send: 'This is the last message'.
ws close.

Be aware that the scheme used is https and not wss. The SocketPlugin which is responsible for the WebSocket support will replace http with ws and https with wss when connecting.

The implementation is a bit unfortunate. The Smalltalk image assumes there are only low level sockets and therefore implements the WebSocket protocol on top of that. Within a browser no low level sockets are available. The SocketPlugin will therefore 'reverse' or 'fake' the WebSocket protocol handling.

The WebSocket handshake protocol is faked within the plugin and a regular WebSocket connection is set up with the other party resulting in a real handshake. When a (WebSocket) message is sent from the Smalltalk runtime it will be packed inside a frame (fragment). The SocketPlugin will extract the message from the frame and send its payload using the WebSocket object (which will put it into a frame again). A bit of unnecessary byte and bit fiddling unfortunately.

[*] The PR https://github.com/bertfreudenberg/SqueakJS/pull/88 needs to be applied, otherwise name resolving becomes an issue. On Cuis the WebClient Feature needs to be loaded explicitly. This is not tested on Pharo since I did not get the Pharo image with Zinc running on SqueakJS. Did not put much effort in it though (my purpose is to get a tiny headless Smalltalk image running inside the browser acting as my script engine and allowing me to manipulate the DOM).

ErikOnBike commented 4 years ago

Same issue with Xvfb (seems persistent) as in https://github.com/bertfreudenberg/SqueakJS/pull/88

ErikOnBike commented 4 years ago

This PR is now part of the modularised SqueakJS version. Closing this PR.