mirror of
https://github.com/mistricky/codesnap.nvim.git
synced 2024-12-27 03:46:29 +00:00
[Feat] ws server for send message to client when received message which
from neovim
This commit is contained in:
parent
9a73beb12f
commit
4b3581230d
29 changed files with 32851 additions and 0 deletions
23
snap-client/.gitignore
vendored
Normal file
23
snap-client/.gitignore
vendored
Normal file
|
@ -0,0 +1,23 @@
|
|||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
46
snap-client/README.md
Normal file
46
snap-client/README.md
Normal file
|
@ -0,0 +1,46 @@
|
|||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
30775
snap-client/package-lock.json
generated
Normal file
30775
snap-client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
49
snap-client/package.json
Normal file
49
snap-client/package.json
Normal file
|
@ -0,0 +1,49 @@
|
|||
{
|
||||
"name": "my-app",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.18.81",
|
||||
"@types/react": "^18.2.55",
|
||||
"@types/react-dom": "^18.2.19",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"typescript": "^4.9.5",
|
||||
"web-vitals": "^2.1.4",
|
||||
"react-use-websocket": "^3.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "npm run tailwindcss:compile && react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject",
|
||||
"tailwindcss:watch": "npm run tailwindcss:compile -- -w",
|
||||
"tailwindcss:compile": "tailwindcss -i ./src/input.css -o ./src/output.css"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"tailwindcss": "^3.4.1"
|
||||
}
|
||||
}
|
BIN
snap-client/public/favicon.ico
Normal file
BIN
snap-client/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 3.8 KiB |
43
snap-client/public/index.html
Normal file
43
snap-client/public/index.html
Normal file
|
@ -0,0 +1,43 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
BIN
snap-client/public/logo192.png
Normal file
BIN
snap-client/public/logo192.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 5.2 KiB |
BIN
snap-client/public/logo512.png
Normal file
BIN
snap-client/public/logo512.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 9.4 KiB |
25
snap-client/public/manifest.json
Normal file
25
snap-client/public/manifest.json
Normal file
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
3
snap-client/public/robots.txt
Normal file
3
snap-client/public/robots.txt
Normal file
|
@ -0,0 +1,3 @@
|
|||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
25
snap-client/src/app.tsx
Normal file
25
snap-client/src/app.tsx
Normal file
|
@ -0,0 +1,25 @@
|
|||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import useWebSocket, { ReadyState } from "react-use-websocket";
|
||||
|
||||
function App() {
|
||||
const [socketUrl, setSocketUrl] = useState("ws://127.0.0.1:8080/ws");
|
||||
const [messageHistory, setMessageHistory] = useState([]);
|
||||
const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);
|
||||
|
||||
const handleClickSendMessage = useCallback(() => {
|
||||
sendMessage("Hello");
|
||||
}, []);
|
||||
|
||||
console.info(lastMessage);
|
||||
|
||||
return (
|
||||
<div className="App">
|
||||
<span className="text-3xl font-bold underline">
|
||||
{lastMessage?.data ?? ""}
|
||||
</span>
|
||||
<button onClick={handleClickSendMessage}>Send</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
1
snap-client/src/components/control-bar.tsx
Normal file
1
snap-client/src/components/control-bar.tsx
Normal file
|
@ -0,0 +1 @@
|
|||
export const ControlBar = {};
|
1
snap-client/src/components/index.ts
Normal file
1
snap-client/src/components/index.ts
Normal file
|
@ -0,0 +1 @@
|
|||
export * from "./control-bar";
|
19
snap-client/src/index.tsx
Normal file
19
snap-client/src/index.tsx
Normal file
|
@ -0,0 +1,19 @@
|
|||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import "./output.css";
|
||||
import App from "./app";
|
||||
import reportWebVitals from "./reportWebVitals";
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById("root") as HTMLElement,
|
||||
);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
4
snap-client/src/input.css
Normal file
4
snap-client/src/input.css
Normal file
|
@ -0,0 +1,4 @@
|
|||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
1
snap-client/src/react-app-env.d.ts
vendored
Normal file
1
snap-client/src/react-app-env.d.ts
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/// <reference types="react-scripts" />
|
15
snap-client/src/reportWebVitals.ts
Normal file
15
snap-client/src/reportWebVitals.ts
Normal file
|
@ -0,0 +1,15 @@
|
|||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
5
snap-client/src/setupTests.ts
Normal file
5
snap-client/src/setupTests.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom';
|
9
snap-client/tailwind.config.ts
Normal file
9
snap-client/tailwind.config.ts
Normal file
|
@ -0,0 +1,9 @@
|
|||
import type { Config } from "tailwindcss";
|
||||
|
||||
export default {
|
||||
content: ["./src/**/*.{js,jsx,ts,tsx}"],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
} satisfies Config;
|
26
snap-client/tsconfig.json
Normal file
26
snap-client/tsconfig.json
Normal file
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
1402
snap-server/Cargo.lock
generated
Normal file
1402
snap-server/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
15
snap-server/Cargo.toml
Normal file
15
snap-server/Cargo.toml
Normal file
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "snap-server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix = "0.13.3"
|
||||
actix-web = "4.5.1"
|
||||
actix-web-actors = "4.3.0"
|
||||
neovim-lib = "0.6.1"
|
||||
rand = "0.8.5"
|
||||
serde = {version = "1.0.196", features = ["derive", "serde_derive", "std"]}
|
||||
serde_json = "1.0.113"
|
28
snap-server/src/event.rs
Normal file
28
snap-server/src/event.rs
Normal file
|
@ -0,0 +1,28 @@
|
|||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Event<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
name: String,
|
||||
data: T,
|
||||
}
|
||||
|
||||
impl<T> Event<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
pub fn new(name: String, data: T) -> Event<T> {
|
||||
Event { name, data }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Into<String> for Event<T>
|
||||
where
|
||||
T: Serialize,
|
||||
{
|
||||
fn into(self) -> String {
|
||||
serde_json::to_string(&self).unwrap()
|
||||
}
|
||||
}
|
64
snap-server/src/event_handler.rs
Normal file
64
snap-server/src/event_handler.rs
Normal file
|
@ -0,0 +1,64 @@
|
|||
mod messages;
|
||||
pub mod neovim;
|
||||
|
||||
use actix::{Actor, Addr, AsyncContext, Context};
|
||||
pub use messages::Message;
|
||||
use neovim::Neovim;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
event::Event,
|
||||
server::{ClientMessage, Server},
|
||||
};
|
||||
|
||||
pub struct EventHandler {
|
||||
neovim: Arc<Mutex<Neovim>>,
|
||||
server: Arc<Addr<Server>>,
|
||||
}
|
||||
|
||||
impl Actor for EventHandler {
|
||||
type Context = Context<Self>;
|
||||
|
||||
fn started(&mut self, _: &mut Self::Context) {
|
||||
self.start_listen();
|
||||
}
|
||||
}
|
||||
|
||||
impl EventHandler {
|
||||
pub fn new(neovim: Arc<Mutex<Neovim>>, server: Arc<Addr<Server>>) -> EventHandler {
|
||||
EventHandler { neovim, server }
|
||||
}
|
||||
|
||||
pub fn start_listen(&mut self) {
|
||||
let receiver = self.neovim.lock().unwrap().create_receiver();
|
||||
|
||||
for (event_name, values) in receiver {
|
||||
match Message::from(event_name.clone()) {
|
||||
Message::PreviewCode => self.server.do_send(ClientMessage {
|
||||
msg: Event::new(
|
||||
"hello".to_string(),
|
||||
serde_json::from_str::<String>(
|
||||
values
|
||||
.iter()
|
||||
.map(|value| value.to_string())
|
||||
.collect::<Vec<String>>()
|
||||
.first()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.into(),
|
||||
}),
|
||||
Message::Unknown => self
|
||||
.neovim
|
||||
.lock()
|
||||
.unwrap()
|
||||
.print(&format!("Unhandled event which name is {}", &event_name)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
16
snap-server/src/event_handler/messages.rs
Normal file
16
snap-server/src/event_handler/messages.rs
Normal file
|
@ -0,0 +1,16 @@
|
|||
#[derive(PartialEq, Hash)]
|
||||
pub enum Message {
|
||||
PreviewCode,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl Eq for Message {}
|
||||
|
||||
impl From<String> for Message {
|
||||
fn from(value: String) -> Self {
|
||||
match value.as_str() {
|
||||
"preview_code" => Message::PreviewCode,
|
||||
_ => Message::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
25
snap-server/src/event_handler/neovim.rs
Normal file
25
snap-server/src/event_handler/neovim.rs
Normal file
|
@ -0,0 +1,25 @@
|
|||
use neovim_lib::{NeovimApi, Session, Value};
|
||||
use std::sync::mpsc;
|
||||
|
||||
pub struct Neovim {
|
||||
pub instance: neovim_lib::Neovim,
|
||||
}
|
||||
|
||||
impl Neovim {
|
||||
pub fn new() -> Neovim {
|
||||
let session = Session::new_parent().unwrap();
|
||||
let instance = neovim_lib::Neovim::new(session);
|
||||
|
||||
Neovim { instance }
|
||||
}
|
||||
|
||||
pub fn create_receiver(&mut self) -> mpsc::Receiver<(String, Vec<Value>)> {
|
||||
return self.instance.session.start_event_loop_channel();
|
||||
}
|
||||
|
||||
pub fn print(&mut self, message: &str) {
|
||||
self.instance
|
||||
.command(&format!("lua print(\"{}\")", message))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
45
snap-server/src/main.rs
Normal file
45
snap-server/src/main.rs
Normal file
|
@ -0,0 +1,45 @@
|
|||
mod event;
|
||||
mod event_handler;
|
||||
mod server;
|
||||
mod session;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use actix::{Actor, Addr, Arbiter, StreamHandler};
|
||||
use actix_web::{
|
||||
web::{self, Data, Payload},
|
||||
App, Error, HttpRequest, HttpResponse, HttpServer,
|
||||
};
|
||||
use actix_web_actors::ws;
|
||||
use event_handler::neovim::Neovim;
|
||||
use event_handler::{EventHandler, Message};
|
||||
use server::Server;
|
||||
use session::Session;
|
||||
|
||||
async fn index(
|
||||
req: HttpRequest,
|
||||
stream: Payload,
|
||||
server: Data<Arc<Addr<Server>>>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
ws::start(Session::new(server), &req, stream)
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let neovim = Arc::new(Mutex::new(Neovim::new()));
|
||||
let server = Arc::new(Server::new(neovim.clone()).start());
|
||||
let cloned_server = Arc::clone(&server);
|
||||
|
||||
Arbiter::new().spawn(async {
|
||||
EventHandler::new(neovim, cloned_server).start();
|
||||
});
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.app_data(web::Data::new(server.clone()))
|
||||
.route("/ws", web::get().to(index))
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.run()
|
||||
.await
|
||||
}
|
86
snap-server/src/server.rs
Normal file
86
snap-server/src/server.rs
Normal file
|
@ -0,0 +1,86 @@
|
|||
use actix::{Actor, Context, Handler, Message, Recipient};
|
||||
use rand::{rngs::ThreadRng, Rng};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::event_handler::neovim::Neovim;
|
||||
|
||||
type SessionID = usize;
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
pub struct ServerMessage(pub String);
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(usize)]
|
||||
pub struct Connect {
|
||||
pub addr: Recipient<ServerMessage>,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
pub struct Disconnect {
|
||||
pub id: usize,
|
||||
}
|
||||
|
||||
#[derive(Message)]
|
||||
#[rtype(result = "()")]
|
||||
pub struct ClientMessage {
|
||||
pub msg: String,
|
||||
}
|
||||
|
||||
pub struct Server {
|
||||
rng: ThreadRng,
|
||||
sessions: HashMap<SessionID, Recipient<ServerMessage>>,
|
||||
neovim: Arc<Mutex<Neovim>>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub fn new(neovim: Arc<Mutex<Neovim>>) -> Server {
|
||||
Server {
|
||||
rng: rand::thread_rng(),
|
||||
sessions: HashMap::new(),
|
||||
neovim,
|
||||
}
|
||||
}
|
||||
|
||||
fn send_message_to_clients(&self, message: &str) {
|
||||
for (_, session) in &self.sessions {
|
||||
session.do_send(ServerMessage(message.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for Server {
|
||||
type Context = Context<Self>;
|
||||
}
|
||||
|
||||
impl Handler<Connect> for Server {
|
||||
type Result = SessionID;
|
||||
|
||||
fn handle(&mut self, msg: Connect, _: &mut Self::Context) -> Self::Result {
|
||||
let id = self.rng.gen::<SessionID>();
|
||||
|
||||
self.sessions.insert(id, msg.addr);
|
||||
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<Disconnect> for Server {
|
||||
type Result = ();
|
||||
|
||||
fn handle(&mut self, msg: Disconnect, _: &mut Self::Context) -> Self::Result {
|
||||
self.sessions.remove(&msg.id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<ClientMessage> for Server {
|
||||
type Result = ();
|
||||
|
||||
fn handle(&mut self, msg: ClientMessage, _: &mut Self::Context) -> Self::Result {
|
||||
self.send_message_to_clients(&msg.msg)
|
||||
}
|
||||
}
|
100
snap-server/src/session.rs
Normal file
100
snap-server/src/session.rs
Normal file
|
@ -0,0 +1,100 @@
|
|||
use crate::server::{ClientMessage, Connect, Disconnect, Server, ServerMessage};
|
||||
use actix::{
|
||||
dev::ContextFutureSpawner, fut, Actor, ActorContext, ActorFutureExt, Addr, AsyncContext,
|
||||
Handler, Running, StreamHandler, WrapFuture,
|
||||
};
|
||||
use actix_web::web::Data;
|
||||
use actix_web_actors::ws;
|
||||
use std::{
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub struct Session {
|
||||
id: usize,
|
||||
server: Arc<Addr<Server>>,
|
||||
heartbeat: Instant,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new(server: Data<Arc<Addr<Server>>>) -> Session {
|
||||
Session {
|
||||
id: 0,
|
||||
server: server.get_ref().clone(),
|
||||
heartbeat: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn heartbeat(&self, ctx: &mut ws::WebsocketContext<Self>) {
|
||||
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
|
||||
// check client heartbeats
|
||||
if Instant::now().duration_since(act.heartbeat) > CLIENT_TIMEOUT {
|
||||
act.server.do_send(Disconnect { id: act.id });
|
||||
|
||||
ctx.stop();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.ping(b"");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for Session {
|
||||
type Context = ws::WebsocketContext<Self>;
|
||||
|
||||
fn started(&mut self, ctx: &mut Self::Context) {
|
||||
self.heartbeat(ctx);
|
||||
self.server
|
||||
.send(Connect {
|
||||
addr: ctx.address().recipient(),
|
||||
})
|
||||
.into_actor(self)
|
||||
.then(|res, act, ctx| {
|
||||
match res {
|
||||
Ok(res) => act.id = res,
|
||||
_ => ctx.stop(),
|
||||
}
|
||||
fut::ready(())
|
||||
})
|
||||
.wait(ctx);
|
||||
}
|
||||
|
||||
fn stopping(&mut self, _: &mut Self::Context) -> Running {
|
||||
self.server.do_send(Disconnect { id: self.id });
|
||||
Running::Stop
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler<ServerMessage> for Session {
|
||||
type Result = ();
|
||||
|
||||
fn handle(&mut self, msg: ServerMessage, ctx: &mut Self::Context) {
|
||||
ctx.text(msg.0);
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Session {
|
||||
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
|
||||
match msg {
|
||||
Ok(ws::Message::Ping(msg)) => {
|
||||
self.heartbeat = Instant::now();
|
||||
ctx.pong(&msg);
|
||||
}
|
||||
Ok(ws::Message::Pong(_)) => {
|
||||
self.heartbeat = Instant::now();
|
||||
}
|
||||
Ok(ws::Message::Text(text)) => {
|
||||
self.server.do_send(ClientMessage {
|
||||
msg: "aaaaa".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue