Browse Source

Add server properties

new_protocol
ThePerkinrex 5 years ago
parent
commit
24980707ec
No known key found for this signature in database GPG Key ID: 1F45A7C4BFB41607
  1. 5
      protobuf/game.proto
  2. 3
      server/.gitignore
  3. 2
      server/Cargo.toml
  4. 19
      server/schema/server-properties.json
  5. 3
      server/src/games/mod.rs
  6. 17
      server/src/grpc.rs
  7. 43
      server/src/grpc/game.rs
  8. 85
      server/src/logger.rs
  9. 6
      server/src/main.rs
  10. 70
      server/src/server_properties.rs
  11. 37
      unity/Assets/Scripts/Client.cs
  12. 4
      unity/Assets/Scripts/MainMenuController.cs
  13. 85
      unity/Assets/Scripts/grpc/Game.cs
  14. 50
      unity/Assets/Scripts/grpc/GameGrpc.cs

5
protobuf/game.proto

@ -4,7 +4,8 @@ package game;
// Connection utilities to get a client_id
service Connection {
rpc connect(Username) returns(UserID);
rpc name(Null) returns(Name);
rpc connect(Name) returns(UserID);
rpc joinLobbyWithCode(LobbyCode) returns(Null);
rpc joinLobbyWithoutCode(Null) returns(LobbyCode);
}
@ -22,7 +23,7 @@ message UserID {
string id = 1;
}
message Username {
message Name {
string name = 1;
}

3
server/.gitignore

@ -2,4 +2,5 @@
Cargo.lock
db.sqlite*
/games
output.log
output.log
properties.json

2
server/Cargo.toml

@ -30,7 +30,7 @@ sqlx = { version = "0.3", default-features = false, features = [ "runtime-tokio"
# TUI
crossterm = "0.18.2"
log = "0.4.11"
fern = "0.6.0"
fern = {version = "0.6.0", features = ["colored"]}
chrono = "0.4.19"
[build-dependencies]
# Grpc codegen

19
server/schema/server-properties.json

@ -0,0 +1,19 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ServerProperties",
"type": "object",
"properties": {
"addr": {
"default": "0.0.0.0:50052",
"type": "string"
},
"name": {
"default": "Spah's sappin' mah sentreh",
"type": "string"
},
"use_colors": {
"default": true,
"type": "boolean"
}
}
}

3
server/src/games/mod.rs

@ -1,6 +1,3 @@
use rhai::AST;
use log::info;
use std::fs::read_dir;
mod config;
mod run;

17
server/src/grpc.rs

@ -8,17 +8,18 @@ mod game;
use game::connection_server::{Connection, ConnectionServer};
use game::lobby_server::{Lobby, LobbyServer};
use game::{LobbyCode, Null, UserId, Username, CardId, Image};
use game::{LobbyCode, Null, UserId, Name, CardId, Image};
use crate::db;
pub struct ConnectionService {
conn: Arc<db::DbPool>,
properties: Arc<crate::server_properties::ServerProperties>
}
#[tonic::async_trait]
impl Connection for ConnectionService {
async fn connect(&self, request: Request<Username>) -> Result<Response<UserId>, Status> {
async fn connect(&self, request: Request<Name>) -> Result<Response<UserId>, Status> {
let name = request.into_inner().name;
let mut conn = self.conn.acquire().await;
let uuid = conn.add_user(&name).await;
@ -59,7 +60,12 @@ impl Connection for ConnectionService {
Ok(Response::new(LobbyCode{code: lobby}))
}
async fn name(
&self,
_request: Request<Null>,
) -> Result<Response<game::Name>, Status> {
Ok(Response::new(game::Name {name: self.properties.name.clone() }))
}
}
@ -116,9 +122,10 @@ impl Lobby for LobbyService {
}
}
pub async fn start(pool: db::DbPool, games: Vec<crate::games::Game>) {
pub async fn start(pool: db::DbPool, games: Vec<crate::games::Game>, properties: crate::server_properties::ServerProperties) {
let arc = Arc::new(pool);
let connection = ConnectionService { conn: arc.clone() };
let properties = Arc::new(properties);
let connection = ConnectionService { conn: arc.clone(), properties };
let lobby = LobbyService {conn: arc.clone(), games: Arc::new(games)};
Server::builder()

43
server/src/grpc/game.rs

@ -4,7 +4,7 @@ pub struct UserId {
pub id: std::string::String,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Username {
pub struct Name {
#[prost(string, tag = "1")]
pub name: std::string::String,
}
@ -66,9 +66,13 @@ pub mod connection_server {
#[doc = "Generated trait containing gRPC methods that should be implemented for use with ConnectionServer."]
#[async_trait]
pub trait Connection: Send + Sync + 'static {
async fn name(
&self,
request: tonic::Request<super::Null>,
) -> Result<tonic::Response<super::Name>, tonic::Status>;
async fn connect(
&self,
request: tonic::Request<super::Username>,
request: tonic::Request<super::Name>,
) -> Result<tonic::Response<super::UserId>, tonic::Status>;
async fn join_lobby_with_code(
&self,
@ -112,16 +116,41 @@ pub mod connection_server {
fn call(&mut self, req: http::Request<B>) -> Self::Future {
let inner = self.inner.clone();
match req.uri().path() {
"/game.Connection/name" => {
#[allow(non_camel_case_types)]
struct nameSvc<T: Connection>(pub Arc<T>);
impl<T: Connection> tonic::server::UnaryService<super::Null> for nameSvc<T> {
type Response = super::Name;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(&mut self, request: tonic::Request<super::Null>) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).name(request).await };
Box::pin(fut)
}
}
let inner = self.inner.clone();
let fut = async move {
let interceptor = inner.1.clone();
let inner = inner.0;
let method = nameSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = if let Some(interceptor) = interceptor {
tonic::server::Grpc::with_interceptor(codec, interceptor)
} else {
tonic::server::Grpc::new(codec)
};
let res = grpc.unary(method, req).await;
Ok(res)
};
Box::pin(fut)
}
"/game.Connection/connect" => {
#[allow(non_camel_case_types)]
struct connectSvc<T: Connection>(pub Arc<T>);
impl<T: Connection> tonic::server::UnaryService<super::Username> for connectSvc<T> {
impl<T: Connection> tonic::server::UnaryService<super::Name> for connectSvc<T> {
type Response = super::UserId;
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
fn call(
&mut self,
request: tonic::Request<super::Username>,
) -> Self::Future {
fn call(&mut self, request: tonic::Request<super::Name>) -> Self::Future {
let inner = self.0.clone();
let fut = async move { (*inner).connect(request).await };
Box::pin(fut)

85
server/src/logger.rs

@ -10,35 +10,63 @@ use crossterm::{
terminal::{Clear, ClearType},
};
use fern::colors::{ColoredLevelConfig, Color};
pub fn setup() -> Result<(Close, Stdin<String>), fern::InitError> {
let (stdout, stdin, close, join_handle) = TerminalHandler::new(|x| {
if x == "sv_cheats" {
log::info!("CHEATS ENABLED")
}
x
});
});
let colors_line = ColoredLevelConfig::new()
.error(Color::Red)
.warn(Color::Yellow)
// we actually don't need to specify the color for debug and info, they are white by default
.info(Color::White)
.debug(Color::BrightBlack)
// depending on the terminals color scheme, this is the same as the background color
.trace(Color::BrightBlack);
let colors_level = colors_line.clone().info(Color::Green).debug(Color::BrightBlack);
let stdout_logger = fern::Dispatch::new()
.format(move |out, message, record| {
out.finish(format_args!(
"{colors_line}{}[{}{colors_line}][{}] {}\x1B[0m",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
colors_level.clone().color(record.level()),
record.target(),
message,
colors_line = format!("\x1B[{}m", colors_line.clone().get_color(&record.level()).to_fg_str()),
// colors_level = colors_level.clone().get_color(&record.level()).to_fg_str(),
))
})
.level(log::LevelFilter::Debug)
.chain(stdout);
let file = fern::Dispatch::new().format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.level(),
record.target(),
message,
))
})
.chain(
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("output.log")?,
);
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message
))
})
.level(log::LevelFilter::Debug)
.chain(stdout)
.chain(
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("output.log")?,
)
.level_for("h2::codec", log::LevelFilter::Info)
.level_for("tokio::codec", log::LevelFilter::Info)
.level_for("sqlx::query", log::LevelFilter::Info)
.chain(stdout_logger)
.chain(file)
.apply()?;
log::info!("TEST1");
log::info!("TEST2");
log::warn!("TEST1");
log::error!("TEST2");
// std::process::exit(1);
Ok((Close{close, handle: join_handle}, stdin))
}
@ -122,13 +150,16 @@ where
KeyCode::Char(c) => self.command.push(c),
KeyCode::Backspace => {self.command.pop();},
KeyCode::Enter => {
log::info!(target: "COMMAND", "{}", self.command);
match self.stdin.send((self.handler)(self.command.clone())) {
Ok(_) => (),
Err(e) => log::error!("{}", e),
};
self.lines.push(format!(" >> {}", self.command));
self.command = String::new();
}
}
KeyCode::Esc => {
self.lines.scroll_to_bottom();
}
_ => ()
}
},
@ -244,14 +275,20 @@ impl<T> LimitedVec<T> {
}
fn scroll_up(&mut self) {
if self.pos + 1 < self.inner.len() {
if self.pos + self.size < self.inner.len() {
// log::info!("SCROLLING UP");
self.pos += 1;
}
}
fn scroll_down(&mut self) {
if self.pos > 0 {
// log::info!("SCROLLING DOWN");
self.pos -= 1;
}
}
fn scroll_to_bottom(&mut self) {
self.pos = 0;
}
}

6
server/src/main.rs

@ -2,9 +2,12 @@ mod grpc;
mod db;
mod games;
mod logger;
mod server_properties;
#[tokio::main]
async fn main() {
server_properties::setup();
let p = server_properties::ServerProperties::load();
let (close, _stdin) = logger::setup().unwrap();
// protobuf::route_guide_grpc::RouteGuid
// for i in 0..100 {
@ -26,7 +29,6 @@ async fn main() {
// println!("{}", conn.add_user("Hi").await);
// println!("{:?}", conn.users().await);
// conn.close().await;
grpc::start(pool, games).await;
grpc::start(pool, games, p).await;
close.close();
}

70
server/src/server_properties.rs

@ -0,0 +1,70 @@
use std::net::SocketAddr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone)]
pub struct ServerProperties {
#[serde(default = "default_name")]
pub name: String,
#[serde(default = "default_addr")]
pub addr: SocketAddr,
#[serde(default = "default_colors")]
pub use_colors: bool,
}
impl ServerProperties {
pub fn load() -> Self {
serde_json::from_str(&match std::fs::read_to_string("properties.json") {
Ok(v) => v,
Err(e) => {
println!("properties.json parsing error: {}", e);
std::process::exit(1)
}
})
.unwrap()
}
}
impl Default for ServerProperties {
fn default() -> Self {
Self {
name: default_name(),
addr: default_addr(),
use_colors: default_colors(),
}
}
}
const fn default_colors() -> bool {
true
}
fn default_addr() -> SocketAddr {
"0.0.0.0:50052".parse().unwrap()
}
fn default_name() -> String {
"Spah's sappin' mah sentreh".into()
}
pub fn setup() {
if cfg!(debug_assertions) {
if let Ok(e) = std::env::var("CARGO_MANIFEST_DIR") {
std::fs::write(
AsRef::<std::path::Path>::as_ref(&e)
.join("schema")
.join("server-properties.json"),
serde_json::to_string_pretty(&schemars::schema_for!(ServerProperties)).unwrap(),
)
.unwrap()
}
}
if !std::path::PathBuf::from("properties.json").exists() {
std::fs::write("properties.json", serde_json::to_string_pretty(&ServerProperties::default()).unwrap()).unwrap();
}
if !std::path::PathBuf::from("games").exists() {
std::fs::create_dir("games").unwrap();
}
}

37
unity/Assets/Scripts/Client.cs

@ -1,10 +1,12 @@
using Grpc.Core;
// using UnityEngine;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
public static class Client
{
private static Connection reference;
public static void Connect(string name, string address="127.0.0.1:50052")
public static void Connect(string name, string address = "127.0.0.1:50052")
{
reference = new Connection(name, address);
}
@ -35,7 +37,11 @@ public static class Client
channel = new Channel(address, ChannelCredentials.Insecure);
connection = new Game.Connection.ConnectionClient(channel);
lobby_client = new Game.Lobby.LobbyClient(channel);
connId = connection.connect(new Game.Username { Name = user }).Id;
connId = connection.connect(new Game.Name { Name_ = user }).Id;
}
public string Name() {
return connection.name(new Game.Null()).Name_;
}
public void JoinLobby(string code)
@ -62,9 +68,32 @@ public static class Client
}
}
public List<Game.Game> getGames()
{
AsyncServerStreamingCall<Game.Game> stream = lobby_client.getGames(new Game.Null());
List<Game.Game> l = new List<Game.Game>();
while (runSync(stream.ResponseStream.MoveNext()))
{
Game.Game g = stream.ResponseStream.Current;
l.Add(g);
// Debug.Log("Received " + feature.ToString());
}
// Debug.Log(stream.ResponseStream.Current);
return l;
}
static T runSync<T>(Task<T> task)
{
task.Wait();
return task.Result;
}
public void Close()
{
channel.ShutdownAsync().Wait();
}
}
}
}

4
unity/Assets/Scripts/MainMenuController.cs

@ -39,6 +39,10 @@ public class MainMenuController : MonoBehaviour {
Client.Connect(username.text);
conn = Client.GetConnection();
}
foreach (Game.Game g in conn.getGames()) {
Debug.Log(g.ToString());
}
if (conn != null) {
mainMenu.SetActive(false);

85
unity/Assets/Scripts/grpc/Game.cs

@ -24,28 +24,29 @@ namespace Game {
static GameReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgpnYW1lLnByb3RvEgRnYW1lIhQKBlVzZXJJRBIKCgJpZBgBIAEoCSIYCghV",
"c2VybmFtZRIMCgRuYW1lGAEgASgJIgYKBE51bGwiKAoGQ2FyZElEEg4KBmdh",
"bWVJZBgBIAEoBBIOCgZjYXJkSWQYAiABKAkiGAoFSW1hZ2USDwoHY29udGVu",
"dBgBIAEoDCIZCglMb2JieUNvZGUSDAoEY29kZRgBIAEoDSJCCgRHYW1lEgwK",
"BG5hbWUYASABKAkSDwoHdmVyc2lvbhgCIAEoCRIPCgdhdXRob3JzGAMgAygJ",
"EgoKAmlkGAQgASgEIhIKBFZvdGUSCgoCaWQYASABKAQiWQoLTG9iYnlTdGF0",
"dXMSGQoFdm90ZXMYASADKAsyCi5nYW1lLlZvdGUSGwoFcmVhZHkYAiADKAsy",
"DC5nYW1lLlBsYXllchISCgppc1N0YXJ0aW5nGAMgASgIIiIKBlBsYXllchIM",
"CgRuYW1lGAEgASgJEgoKAmlkGAIgASgEMpwBCgpDb25uZWN0aW9uEicKB2Nv",
"bm5lY3QSDi5nYW1lLlVzZXJuYW1lGgwuZ2FtZS5Vc2VySUQSMAoRam9pbkxv",
"YmJ5V2l0aENvZGUSDy5nYW1lLkxvYmJ5Q29kZRoKLmdhbWUuTnVsbBIzChRq",
"b2luTG9iYnlXaXRob3V0Q29kZRIKLmdhbWUuTnVsbBoPLmdhbWUuTG9iYnlD",
"b2RlMsIBCgVMb2JieRIkCghnZXRHYW1lcxIKLmdhbWUuTnVsbBoKLmdhbWUu",
"R2FtZTABEikKDGdldENhcmRJbWFnZRIMLmdhbWUuQ2FyZElEGgsuZ2FtZS5J",
"bWFnZRIeCgR2b3RlEgouZ2FtZS5Wb3RlGgouZ2FtZS5OdWxsEh8KBXJlYWR5",
"EgouZ2FtZS5OdWxsGgouZ2FtZS5OdWxsEicKBnN0YXR1cxIKLmdhbWUuTnVs",
"bBoRLmdhbWUuTG9iYnlTdGF0dXNiBnByb3RvMw=="));
"CgpnYW1lLnByb3RvEgRnYW1lIhQKBlVzZXJJRBIKCgJpZBgBIAEoCSIUCgRO",
"YW1lEgwKBG5hbWUYASABKAkiBgoETnVsbCIoCgZDYXJkSUQSDgoGZ2FtZUlk",
"GAEgASgEEg4KBmNhcmRJZBgCIAEoCSIYCgVJbWFnZRIPCgdjb250ZW50GAEg",
"ASgMIhkKCUxvYmJ5Q29kZRIMCgRjb2RlGAEgASgNIkIKBEdhbWUSDAoEbmFt",
"ZRgBIAEoCRIPCgd2ZXJzaW9uGAIgASgJEg8KB2F1dGhvcnMYAyADKAkSCgoC",
"aWQYBCABKAQiEgoEVm90ZRIKCgJpZBgBIAEoBCJZCgtMb2JieVN0YXR1cxIZ",
"CgV2b3RlcxgBIAMoCzIKLmdhbWUuVm90ZRIbCgVyZWFkeRgCIAMoCzIMLmdh",
"bWUuUGxheWVyEhIKCmlzU3RhcnRpbmcYAyABKAgiIgoGUGxheWVyEgwKBG5h",
"bWUYASABKAkSCgoCaWQYAiABKAQyuAEKCkNvbm5lY3Rpb24SHgoEbmFtZRIK",
"LmdhbWUuTnVsbBoKLmdhbWUuTmFtZRIjCgdjb25uZWN0EgouZ2FtZS5OYW1l",
"GgwuZ2FtZS5Vc2VySUQSMAoRam9pbkxvYmJ5V2l0aENvZGUSDy5nYW1lLkxv",
"YmJ5Q29kZRoKLmdhbWUuTnVsbBIzChRqb2luTG9iYnlXaXRob3V0Q29kZRIK",
"LmdhbWUuTnVsbBoPLmdhbWUuTG9iYnlDb2RlMsIBCgVMb2JieRIkCghnZXRH",
"YW1lcxIKLmdhbWUuTnVsbBoKLmdhbWUuR2FtZTABEikKDGdldENhcmRJbWFn",
"ZRIMLmdhbWUuQ2FyZElEGgsuZ2FtZS5JbWFnZRIeCgR2b3RlEgouZ2FtZS5W",
"b3RlGgouZ2FtZS5OdWxsEh8KBXJlYWR5EgouZ2FtZS5OdWxsGgouZ2FtZS5O",
"dWxsEicKBnN0YXR1cxIKLmdhbWUuTnVsbBoRLmdhbWUuTG9iYnlTdGF0dXNi",
"BnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Game.UserID), global::Game.UserID.Parser, new[]{ "Id" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Game.Username), global::Game.Username.Parser, new[]{ "Name" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Game.Name), global::Game.Name.Parser, new[]{ "Name_" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Game.Null), global::Game.Null.Parser, null, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Game.CardID), global::Game.CardID.Parser, new[]{ "GameId", "CardId" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Game.Image), global::Game.Image.Parser, new[]{ "Content" }, null, null, null, null),
@ -232,15 +233,15 @@ namespace Game {
}
public sealed partial class Username : pb::IMessage<Username>
public sealed partial class Name : pb::IMessage<Name>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Username> _parser = new pb::MessageParser<Username>(() => new Username());
private static readonly pb::MessageParser<Name> _parser = new pb::MessageParser<Name>(() => new Name());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Username> Parser { get { return _parser; } }
public static pb::MessageParser<Name> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
@ -253,28 +254,28 @@ namespace Game {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Username() {
public Name() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Username(Username other) : this() {
public Name(Name other) : this() {
name_ = other.name_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Username Clone() {
return new Username(this);
public Name Clone() {
return new Name(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
public const int Name_FieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
public string Name_ {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
@ -283,25 +284,25 @@ namespace Game {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Username);
return Equals(other as Name);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Username other) {
public bool Equals(Name other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Name_ != other.Name_) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Name_.Length != 0) hash ^= Name_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
@ -318,9 +319,9 @@ namespace Game {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
if (Name_.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
output.WriteString(Name_);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
@ -331,9 +332,9 @@ namespace Game {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
if (Name_.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
output.WriteString(Name_);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
@ -344,8 +345,8 @@ namespace Game {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
if (Name_.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name_);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
@ -354,12 +355,12 @@ namespace Game {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Username other) {
public void MergeFrom(Name other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
if (other.Name_.Length != 0) {
Name_ = other.Name_;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
@ -376,7 +377,7 @@ namespace Game {
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
Name_ = input.ReadString();
break;
}
}
@ -394,7 +395,7 @@ namespace Game {
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
Name_ = input.ReadString();
break;
}
}

50
unity/Assets/Scripts/grpc/GameGrpc.cs

@ -45,16 +45,23 @@ namespace Game {
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
static readonly grpc::Marshaller<global::Game.Username> __Marshaller_game_Username = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Username.Parser));
static readonly grpc::Marshaller<global::Game.Null> __Marshaller_game_Null = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Null.Parser));
static readonly grpc::Marshaller<global::Game.Name> __Marshaller_game_Name = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Name.Parser));
static readonly grpc::Marshaller<global::Game.UserID> __Marshaller_game_UserID = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.UserID.Parser));
static readonly grpc::Marshaller<global::Game.LobbyCode> __Marshaller_game_LobbyCode = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.LobbyCode.Parser));
static readonly grpc::Marshaller<global::Game.Null> __Marshaller_game_Null = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Game.Null.Parser));
static readonly grpc::Method<global::Game.Username, global::Game.UserID> __Method_connect = new grpc::Method<global::Game.Username, global::Game.UserID>(
static readonly grpc::Method<global::Game.Null, global::Game.Name> __Method_name = new grpc::Method<global::Game.Null, global::Game.Name>(
grpc::MethodType.Unary,
__ServiceName,
"name",
__Marshaller_game_Null,
__Marshaller_game_Name);
static readonly grpc::Method<global::Game.Name, global::Game.UserID> __Method_connect = new grpc::Method<global::Game.Name, global::Game.UserID>(
grpc::MethodType.Unary,
__ServiceName,
"connect",
__Marshaller_game_Username,
__Marshaller_game_Name,
__Marshaller_game_UserID);
static readonly grpc::Method<global::Game.LobbyCode, global::Game.Null> __Method_joinLobbyWithCode = new grpc::Method<global::Game.LobbyCode, global::Game.Null>(
@ -81,7 +88,12 @@ namespace Game {
[grpc::BindServiceMethod(typeof(Connection), "BindService")]
public abstract partial class ConnectionBase
{
public virtual global::System.Threading.Tasks.Task<global::Game.UserID> connect(global::Game.Username request, grpc::ServerCallContext context)
public virtual global::System.Threading.Tasks.Task<global::Game.Name> name(global::Game.Null request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::Game.UserID> connect(global::Game.Name request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
@ -121,19 +133,35 @@ namespace Game {
{
}
public virtual global::Game.UserID connect(global::Game.Username request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
public virtual global::Game.Name name(global::Game.Null request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return name(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Game.Name name(global::Game.Null request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_name, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Game.Name> nameAsync(global::Game.Null request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return nameAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Game.Name> nameAsync(global::Game.Null request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_name, null, options, request);
}
public virtual global::Game.UserID connect(global::Game.Name request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return connect(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::Game.UserID connect(global::Game.Username request, grpc::CallOptions options)
public virtual global::Game.UserID connect(global::Game.Name request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_connect, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::Game.UserID> connectAsync(global::Game.Username request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
public virtual grpc::AsyncUnaryCall<global::Game.UserID> connectAsync(global::Game.Name request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return connectAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::Game.UserID> connectAsync(global::Game.Username request, grpc::CallOptions options)
public virtual grpc::AsyncUnaryCall<global::Game.UserID> connectAsync(global::Game.Name request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_connect, null, options, request);
}
@ -181,6 +209,7 @@ namespace Game {
public static grpc::ServerServiceDefinition BindService(ConnectionBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_name, serviceImpl.name)
.AddMethod(__Method_connect, serviceImpl.connect)
.AddMethod(__Method_joinLobbyWithCode, serviceImpl.joinLobbyWithCode)
.AddMethod(__Method_joinLobbyWithoutCode, serviceImpl.joinLobbyWithoutCode).Build();
@ -192,7 +221,8 @@ namespace Game {
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static void BindService(grpc::ServiceBinderBase serviceBinder, ConnectionBase serviceImpl)
{
serviceBinder.AddMethod(__Method_connect, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Game.Username, global::Game.UserID>(serviceImpl.connect));
serviceBinder.AddMethod(__Method_name, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Game.Null, global::Game.Name>(serviceImpl.name));
serviceBinder.AddMethod(__Method_connect, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Game.Name, global::Game.UserID>(serviceImpl.connect));
serviceBinder.AddMethod(__Method_joinLobbyWithCode, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Game.LobbyCode, global::Game.Null>(serviceImpl.joinLobbyWithCode));
serviceBinder.AddMethod(__Method_joinLobbyWithoutCode, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Game.Null, global::Game.LobbyCode>(serviceImpl.joinLobbyWithoutCode));
}

Loading…
Cancel
Save