feat(client): MVP Socket.io ping

parent 6f5d8daa
...@@ -9,9 +9,11 @@ ...@@ -9,9 +9,11 @@
}, },
"dependencies": { "dependencies": {
"core-js": "^3.6.4", "core-js": "^3.6.4",
"es6-promise": "^4.2.8",
"socket.io-client": "^2.3.0", "socket.io-client": "^2.3.0",
"vue": "^2.6.11", "vue": "^2.6.11",
"vue-socket.io": "^3.0.7" "vue-socket.io": "^3.0.7",
"vuex": "^3.1.3"
}, },
"devDependencies": { "devDependencies": {
"@vue/cli-plugin-babel": "~4.3.0", "@vue/cli-plugin-babel": "~4.3.0",
......
<template> <template>
<div id="app"> <div id="app">
<img alt="Vue logo" src="./assets/logo.png" /> <img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" /> <HelloWorld msg="Welcome to Menteur!" />
<ListenToSockets />
</div> </div>
</template> </template>
<script> <script>
import HelloWorld from "./components/HelloWorld.vue";
import Vue from 'vue'
import Vuex from 'vuex'
import 'es6-promise/auto' // Needed for Promise polyfill
import VueSocketIO from 'vue-socket.io'
// import Game from "./components/Game";
import HelloWorld from "./components/HelloWorld";
import ListenToSockets from "./ListenToSockets";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count++
}
}
// TODO: Use actions for VueX-SocketIO integration?
// actions: {
// "<ACTION_PREFIX><EVENT_NAME>"() {
// // do something
// }
// }
});
Vue.use(new VueSocketIO({
debug: true,
connection: 'http://localhost:9042',
vuex: {
store,
actionPrefix: 'SOCKET_',
mutationPrefix: 'SOCKET_'
},
options: { path: "/socket.io/" } //Optional options
}));
export default { export default {
name: "App", name: "App",
components: { components: {
HelloWorld HelloWorld,
ListenToSockets
} }
}; };
</script> </script>
<style> <style>
......
<template>
<div>
<p v-if="isConnected">We're connected to the server!</p>
<p v-if="!isConnected">We're not connected yet...</p>
<p>Message from server: "{{socketMessage}}"</p>
<button @click="pingServer()">Ping Server</button>
<button @click="logOn()">LogOn</button>
<button @click="logOff()">LogOff</button>
</div>
</template>
<script>
export default {
data() {
return {
isConnected: false,
socketMessage: 'NO_MESSAGE_YET'
}
},
sockets: {
connect() {
// Fired when the socket connects.
this.isConnected = true;
console.log("login");
},
disconnect() {
this.isConnected = false;
console.log("logoff");
},
customEmit: function (data) {
console.log('this method was fired by the socket server. Data:', data);
},
// Fired when the server sends something on the "messageChannel" channel.
messageChannel(data) {
this.socketMessage = data;
console.log("Message received:", data, "!");
}
},
methods: {
pingServer() {
// Send the "pingServer" event to the server.
this.$socket.emit('pingServer', 'PING!');
console.log("Ping sent!");
},
logOn() {
this.$socket.onconnect();
},
logOff() {
this.$socket.ondisconnect();
}
}
}
</script>
\ No newline at end of file
<template> <template>
<div class="hello"> <div class="hello">
<h1>{{ msg }}</h1> <h1>Hello Vue! {{ msg }}</h1>
<p> <p>
For a guide and recipes on how to configure / customize this project,<br /> For a guide and recipes on how to configure / customize this project,<br />
check out the check out the
...@@ -27,62 +27,6 @@ ...@@ -27,62 +27,6 @@
> >
</li> </li>
</ul> </ul>
<h3>Essential Links</h3>
<ul>
<li>
<a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a>
</li>
<li>
<a href="https://forum.vuejs.org" target="_blank" rel="noopener"
>Forum</a
>
</li>
<li>
<a href="https://chat.vuejs.org" target="_blank" rel="noopener"
>Community Chat</a
>
</li>
<li>
<a href="https://twitter.com/vuejs" target="_blank" rel="noopener"
>Twitter</a
>
</li>
<li>
<a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a>
</li>
</ul>
<h3>Ecosystem</h3>
<ul>
<li>
<a href="https://router.vuejs.org" target="_blank" rel="noopener"
>vue-router</a
>
</li>
<li>
<a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a>
</li>
<li>
<a
href="https://github.com/vuejs/vue-devtools#vue-devtools"
target="_blank"
rel="noopener"
>vue-devtools</a
>
</li>
<li>
<a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener"
>vue-loader</a
>
</li>
<li>
<a
href="https://github.com/vuejs/awesome-vue"
target="_blank"
rel="noopener"
>awesome-vue</a
>
</li>
</ul>
</div> </div>
</template> </template>
......
from http.client import HTTPException from http.client import HTTPException
import socketio import socketio
from fastapi import FastAPI, APIRouter, HTTPException from fastapi import FastAPI, APIRouter
from starlette.websockets import WebSocket from fastapi.exceptions import RequestValidationError
from starlette.responses import PlainTextResponse
from starlette.exceptions import HTTPException
from server.model.data import Game from server.model.data import Game
# Game state # Game state
...@@ -21,7 +23,7 @@ sio_asgi_app = socketio.ASGIApp( ...@@ -21,7 +23,7 @@ sio_asgi_app = socketio.ASGIApp(
other_asgi_app=app other_asgi_app=app
) )
app.add_route("/socket.io/", route=sio_asgi_app, methods=['GET', 'POST']) app.add_route("/socket.io/", route=sio_asgi_app, methods=['GET', 'POST'])
app.add_websocket_route("/socket.io/", sio_asgi_app) app.add_websocket_route("/socket.io/", route=sio_asgi_app)
@router.get("/") @router.get("/")
...@@ -38,25 +40,18 @@ async def join(player_name: str): ...@@ -38,25 +40,18 @@ async def join(player_name: str):
raise HTTPException(status_code=403, detail=f"{player_name} already connected, choose another name.") raise HTTPException(status_code=403, detail=f"{player_name} already connected, choose another name.")
@router.post("/ready") app.include_router(router)
async def ready():
pass
@router.post("/play")
async def play():
pass
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=400)
app.include_router(router)
if __name__ == '__main__': if __name__ == '__main__':
import uvicorn import uvicorn
......
...@@ -2,18 +2,27 @@ import socketio ...@@ -2,18 +2,27 @@ import socketio
sio = socketio.AsyncServer( sio = socketio.AsyncServer(
async_mode='asgi', async_mode='asgi',
# cors_allowed_origins=','.join(config.ALLOW_ORIGIN) logger=True,
cors_allowed_origins="*" # FIXME: CSRF Vulnerability
) )
@sio.event @sio.event
def connect(sid, environ): def connect(sid, environ):
print("connect ", sid, environ) print("connect ", sid, environ)
@sio.event @sio.event
async def chat_message(sid, data): async def chat_message(sid, data):
print("message ", data) print("message ", data)
await sio.emit('reply', room=sid) await sio.emit('reply', room=sid)
@sio.on("pingServer")
async def ping_server(sid, data):
print("Ping received:", data)
await sio.emit('messageChannel', "PONG")
@sio.event @sio.event
def disconnect(sid): def disconnect(sid):
print('disconnect ', sid) print('disconnect ', sid)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment