Skip to content

Commit

Permalink
websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
aratama committed Oct 20, 2024
1 parent 3088cdb commit 72a3224
Show file tree
Hide file tree
Showing 17 changed files with 209 additions and 8 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
/dist
/dist
.stage
9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,14 @@ features = [

[dependencies.web-sys]
version = "0.3.70"
features = ["console", "Window", "Storage"]
features = [
"console",
"Window",
"Storage",
"WebSocket",
"MessageEvent",
"ErrorEvent",
]

[dependencies.bevy_rapier2d]
version = "0.27.0"
Expand Down
6 changes: 3 additions & 3 deletions docs/index.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<script integrity=sha384-DXfxbHnmRjXl3uhZSP4S1IWEe3DfX/sHDa2A7iHxmUB6Ag+87PaP8wV2AtDOwHfm src=./restart-audio-context-8127143435824044.js type=module></script><link href=./index-56627a79e0752a1c.css integrity=sha384-m/ivHNojsD/VAvwMMce+fhrN8VxOZuZt5hms1JExuO36KLCDKKRGDtjLXSlnQq0B rel=stylesheet><script nonce="CuZ6N6gVlCtFaHRLASTYew==" type=module>import init, * as bindings from './my_bevy_game-ba276c861f566071.js';
const wasm = await init('./my_bevy_game-ba276c861f566071_bg.wasm');
<script integrity=sha384-DXfxbHnmRjXl3uhZSP4S1IWEe3DfX/sHDa2A7iHxmUB6Ag+87PaP8wV2AtDOwHfm src=./restart-audio-context-8127143435824044.js type=module></script><link href=./index-56627a79e0752a1c.css integrity=sha384-m/ivHNojsD/VAvwMMce+fhrN8VxOZuZt5hms1JExuO36KLCDKKRGDtjLXSlnQq0B rel=stylesheet><script nonce="iGEe4s3oX1SQSqG3f7F0nQ==" type=module>import init, * as bindings from './my_bevy_game-a8b691d97a29bb5e.js';
const wasm = await init('./my_bevy_game-a8b691d97a29bb5e_bg.wasm');


window.wasmBindings = bindings;


dispatchEvent(new CustomEvent("TrunkApplicationStarted", {detail: {wasm}}));</script><title></title><link crossorigin href=./my_bevy_game-ba276c861f566071.js integrity=sha384-V4s1vj0yqE1RFPdVDehr2zhrSjFVg8hUJ+/dMr5hrAOQeCZF2g5g7JpZIG1d5ckp rel=modulepreload><link as=fetch crossorigin href=./my_bevy_game-ba276c861f566071_bg.wasm integrity=sha384-nquPGE8gC/WOGOLHBODKfj+MdmYdAN3BHUDHFPMUcd50rWPXVOyiluRjJ6lU+nBJ rel=preload type=application/wasm></head><body></body></html>
dispatchEvent(new CustomEvent("TrunkApplicationStarted", {detail: {wasm}}));</script><title>Magna Magia 0.1</title><link crossorigin href=./my_bevy_game-a8b691d97a29bb5e.js integrity=sha384-c7UPANyLeFBIKQkwGc9pZehIG28gfpnf9kE/Vdr683uKhr02PXwqPFYoO3SF24xp rel=modulepreload><link as=fetch crossorigin href=./my_bevy_game-a8b691d97a29bb5e_bg.wasm integrity=sha384-j0pisGGUlc2Jc0DvW9XqVuF2CKm1ecxJ3nEL5wBOPpjKkdbeoviN3QE5FQurmU2i rel=preload type=application/wasm></head><body></body></html>
1 change: 1 addition & 0 deletions docs/my_bevy_game-a8b691d97a29bb5e.js

Large diffs are not rendered by default.

Binary file not shown.
1 change: 0 additions & 1 deletion docs/my_bevy_game-ba276c861f566071.js

This file was deleted.

5 changes: 4 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@
<link data-trunk rel="css" href="index.css" />
<link data-trunk rel="copy-dir" href="assets" />
<link data-trunk rel="rust" data-wasm-opt="z" />
<!-- <link data-trunk rel="rust" data-wasm-opt="0" /> -->
<!-- <link data-trunk rel="rust" data-keep-debug /> -->


<!-- ChromeのC/C++ DevTools Supportでデバッグをしたいときは、デバッグ情報を残すために以下のオプションを有効にする -->
<!-- ただしWSLで開発している場合は、WindowsがわのChromeはWSL内のソースファイルを参照できないのでうまくいかない -->
<!-- <link data-trunk rel="rust" data-wasm-opt="0" data-keep-debug /> -->
<title></title>
<title>Magna Magia 0.1</title>
</head>

<body></body>
Expand Down
1 change: 1 addition & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
29 changes: 29 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const WebSocket = require('ws');
const port = process.env.PORT || 3000;
const server = new WebSocket.Server({ port });
console.log(`Server started on port ${port}`);

// https://www.npmjs.com/package/ws
server.on('connection', (ws, req) => {

const ip = req.socket.remoteAddress;

console.log('Client connected, ip address:', ip);

ws.on('error', (e) => {
console.error(e);
});

ws.on('message', (message, isBinary) => {
console.log('received: %s', message);

const data = message.toString().toUpperCase();
// ws.send(`Hello, you sent -> ${message.toString().toUpperCase()}`);

server.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});
37 changes: 37 additions & 0 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "whiteboard",
"version": "1.0.0",
"description": "A simple collaborative whiteboard using socket.io",
"main": "index.js",
"keywords": [],
"dependencies": {
"ws": "^8.18.0"
},
"scripts": {
"start": "node index",
"deploy": "gcloud run deploy magia-server --project=magia --source ."
},
"author": "Damien Arrachequesne",
"license": "MIT"
}
11 changes: 11 additions & 0 deletions server/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO</title>
</head>
<body>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
<script src="./main.js"></script>
</body>
</html>
17 changes: 17 additions & 0 deletions server/public/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use strict';

(function() {
const socket = new WebSocket("ws://localhost:3000");

socket.onopen = () => {
console.log('Connected to server');

socket.send('Hello from client');
};

socket.onmessage = (event) => {
console.log('Message from server', event.data);

socket.send(event.data.toUppserCase());
};
})();
18 changes: 18 additions & 0 deletions server/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
https://github.com/socketio/socket.io/tree/master/examples/whiteboard

# Socket.IO Collaborative Whiteboard

A simple collaborative whiteboard for Socket.IO

## How to use

```
$ npm ci && npm start
```

And point your browser to `http://localhost:3000`. Optionally, specify
a port by supplying the `PORT` env variable.

## Features

- draw on the whiteboard and all other users will see you drawings live
1 change: 1 addition & 0 deletions src/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ mod set;
mod states;
mod tile;
mod wall;
mod websocket;
mod world;
18 changes: 17 additions & 1 deletion src/game/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use super::overlay::*;
use super::player::*;
use super::serialize::*;
use super::states::*;
#[cfg(target_arch = "wasm32")]
use super::websocket::send_to_server;
use super::world::*;
use bevy::asset::{AssetMetaCheck, AssetPlugin};
#[cfg(feature = "debug")]
Expand All @@ -37,7 +39,21 @@ use bevy_rapier2d::prelude::*;
#[cfg(feature = "debug")]
use iyes_perf_ui::PerfUiPlugin;

#[cfg(target_arch = "wasm32")]
use web_sys::console;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;

pub fn run_game() {
#[cfg(target_arch = "wasm32")]
if let Err(err) = send_to_server() {
console::log_1(&JsValue::from_str("Failed to send message to server"));
// console::log_1(
// &JsValue::from_str(&err.as_string().unwrap_or("".to_string())),
// );
}

let mut app = App::new();

app
Expand All @@ -59,7 +75,7 @@ pub fn run_game() {
icon: CursorIcon::Crosshair,
..default()
},
title: "Magia Gene 0.1".to_string(),
title: "Magna Magia 0.1".to_string(),
resizable: false,
enabled_buttons: EnabledButtons {
close: true,
Expand Down
44 changes: 44 additions & 0 deletions src/game/websocket.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#![cfg(target_arch = "wasm32")]

use wasm_bindgen::prelude::*;
use wasm_bindgen::{prelude::Closure, JsValue};
use web_sys::{console, ErrorEvent, MessageEvent, WebSocket};

// https://rustwasm.github.io/wasm-bindgen/examples/websockets.html
pub fn send_to_server() -> Result<(), JsValue> {
let url = "http://127.0.0.1:3000";

console::log_2(&JsValue::from_str("connecting "), &JsValue::from_str(url));

let ws = WebSocket::new(url)?;
let cloned_ws = ws.clone();

console::log_1(&JsValue::from_str("socket created "));

let onmessage_callback = Closure::wrap(Box::new(move |e: MessageEvent| {
console::log_2(&JsValue::from_str("message event"), &e.data());
}) as Box<dyn FnMut(MessageEvent)>);
ws.set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref()));
onmessage_callback.forget();

let onerror_callback = Closure::wrap(Box::new(move |e: ErrorEvent| {
console::log_2(
&JsValue::from_str("error event"),
&JsValue::from_str(e.message().as_str()),
);
}) as Box<dyn FnMut(ErrorEvent)>);
ws.set_onerror(Some(onerror_callback.as_ref().unchecked_ref()));
onerror_callback.forget();

let onopen_callback = Closure::wrap(Box::new(move |_| {
console::log_1(&JsValue::from_str("socket opended"));

cloned_ws.send_with_str("hello from rust");
}) as Box<dyn FnMut(JsValue)>);
ws.set_onopen(Some(onopen_callback.as_ref().unchecked_ref()));
onopen_callback.forget();

console::log_1(&JsValue::from_str("callback initialized "));

Ok(())
}

0 comments on commit 72a3224

Please sign in to comment.