feat(client): MVP Socket.io ping

parent 6f5d8daa
......@@ -9,9 +9,11 @@
},
"dependencies": {
"core-js": "^3.6.4",
"es6-promise": "^4.2.8",
"socket.io-client": "^2.3.0",
"vue": "^2.6.11",
"vue-socket.io": "^3.0.7"
"vue-socket.io": "^3.0.7",
"vuex": "^3.1.3"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.3.0",
......
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
<HelloWorld msg="Welcome to Menteur!" />
<ListenToSockets />
</div>
</template>
<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 {
name: "App",
components: {
HelloWorld
HelloWorld,
ListenToSockets
}
};
</script>
<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>
<div class="hello">
<h1>{{ msg }}</h1>
<h1>Hello Vue! {{ msg }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br />
check out the
......@@ -27,62 +27,6 @@
>
</li>
</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>
</template>
......
from http.client import HTTPException
import socketio
from fastapi import FastAPI, APIRouter, HTTPException
from starlette.websockets import WebSocket
from fastapi import FastAPI, APIRouter
from fastapi.exceptions import RequestValidationError
from starlette.responses import PlainTextResponse
from starlette.exceptions import HTTPException
from server.model.data import Game
# Game state
......@@ -21,7 +23,7 @@ sio_asgi_app = socketio.ASGIApp(
other_asgi_app=app
)
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("/")
......@@ -38,25 +40,18 @@ async def join(player_name: str):
raise HTTPException(status_code=403, detail=f"{player_name} already connected, choose another name.")
@router.post("/ready")
async def ready():
pass
app.include_router(router)
@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__':
import uvicorn
......
......@@ -2,18 +2,27 @@ import socketio
sio = socketio.AsyncServer(
async_mode='asgi',
# cors_allowed_origins=','.join(config.ALLOW_ORIGIN)
logger=True,
cors_allowed_origins="*" # FIXME: CSRF Vulnerability
)
@sio.event
def connect(sid, environ):
print("connect ", sid, environ)
@sio.event
async def chat_message(sid, data):
print("message ", data)
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
def 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