Skip to content
This repository has been archived by the owner on Jun 7, 2022. It is now read-only.

Commit

Permalink
Use network protocol variable to connect.
Browse files Browse the repository at this point in the history
  • Loading branch information
Flone-dnb committed Oct 3, 2021
1 parent 2ea6d6f commit e72df1b
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 34 deletions.
4 changes: 2 additions & 2 deletions res/localization.csv
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ CONNECT_LAYOUT_CONNECT_RESULT_OTHER_ERR,There was an error,Возникла ош
CONNECT_LAYOUT_CONNECT_RESULT_ERR_SERVER_OFFLINE,"Can't connect to the server. Make sure the specified server and port are correct, otherwise the server might be offline.","Не получается подключиться к серверу. Убедитесь, что указанный сервер и порт корректны, иначе, возможно сервер не запущен."
CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_PASSWORD_PART1,"Server reply: wrong password, try again after","Ответ сервера: неверный пароль, попробуйте еще раз через"
CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_PASSWORD_PART2,seconds,секунды
CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_VERSION_PART1,Server reply: your client version,Ответ сервера: версия вашего приложения
CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_VERSION_PART2,"is not supported by this server, the server supports version","не поддерживается этим сервером, сервер поддерживает версию"
CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_VERSION_PART1,Server reply: your client protocol version,Ответ сервера: версия протокола вашего приложения
CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_VERSION_PART2,"is not supported by this server, the server supports protocol version","не поддерживается этим сервером, сервер поддерживает версию протокола"
CONNECT_LAYOUT_CONNECT_RESULT_ERR_USERNAME_TAKEN,"Server reply: somebody with your username already persists on the server, please, choose another username.","Ответ сервера: кто-то с вашим именем уже находится на сервере, пожалуйста, выберите другое имя пользователя."
CONNECT_LAYOUT_CHECK_FIELDS_LENGTH_USERNAME_PART1,The username is too long,Имя пользователя слишком длинное
CONNECT_LAYOUT_CHECK_FIELDS_LENGTH_USERNAME_PART2,characters when the limit is,"символов, в то время как максимум"
Expand Down
Binary file modified res/localization.ods
Binary file not shown.
1 change: 1 addition & 0 deletions src/global_params.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub const CLIENT_CONFIG_FILE_NAME: &str = "silent.config";
pub const CONFIG_FILE_MAGIC_NUMBER: u16 = 51338;
pub const CONFIG_FILE_VERSION: u64 = 2;
pub const NETWORK_PROTOCOL_VERSION: u64 = 0; // server with the same version is considered compatible

pub const TEXT_SIZE: f64 = 18.0;
pub const MESSAGE_AUTHOR_TEXT_SIZE: f64 = 16.0;
Expand Down
4 changes: 2 additions & 2 deletions src/layouts/connect_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ impl ConnectLayout {
.get(LOCALE_CONNECT_LAYOUT_CONNECT_RESULT_ERR_SERVER_OFFLINE)
.unwrap()
.clone(),
ConnectResult::WrongVersion(server_version) => {
ConnectResult::WrongProtocol(server_protocol) => {
format!(
"{} {} {} {}.",
localization
Expand All @@ -317,7 +317,7 @@ impl ConnectLayout {
localization
.get(LOCALE_CONNECT_LAYOUT_CONNECT_RESULT_ERR_WRONG_VERSION_PART2)
.unwrap(),
server_version
server_protocol
)
}
ConnectResult::UsernameTaken => localization
Expand Down
68 changes: 38 additions & 30 deletions src/services/user_tcp_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ pub enum ClientMessageTcp {
UserMessage = 0,
EnterRoom = 1,
KeepAliveCheck = 2,
TryConnect = 3,
}

pub struct UserMessageInfo {
Expand Down Expand Up @@ -91,8 +92,8 @@ pub enum ConnectResult {
IoErr(IoResult),
ErrServerOffline,
UsernameTaken,
SleepWithErr(usize), // sleep time in sec.
WrongVersion(String), // needed protocol
SleepWithErr(usize), // sleep time in sec.
WrongProtocol(u64), // needed protocol
Err(String),
InfoAboutOtherUser(UserInfo, String, u16),
InfoAboutRoom(String),
Expand Down Expand Up @@ -756,25 +757,47 @@ impl UserTcpService {
info_sender: std::sync::mpsc::Sender<ConnectInfo>,
) -> ConnectResult {
// Prepare initial send buffer:
// (u16): size of the version string,
// (size): version string,
// (u16): message id (TryConnect)
// (u64): net protocol version
// (u16): size of the username,
// (size): username string,
// (u16): size of the password string,
// (size): password string.
let ver_str_len = env!("CARGO_PKG_VERSION").len() as u16;

// Prepare data ID buffer.
let data_id = ClientMessageTcp::TryConnect.to_u16();
if data_id.is_none() {
return ConnectResult::IoErr(IoResult::Err(format!(
"ClientMessage::TryConnect.to_u16() failed at [{}, {}]",
file!(),
line!()
)));
}
let data_id = data_id.unwrap();
let data_id_buf = u16::encode::<u16>(&data_id);
if let Err(e) = data_id_buf {
return ConnectResult::Err(format!(
"u16::encode::<u16>() failed on value {}, error: {} at [{}, {}]",
data_id,
e,
file!(),
line!()
));
}
let mut data_id_buf = data_id_buf.unwrap();

let net_protocol_version = NETWORK_PROTOCOL_VERSION;
let name_str_len = self.user_info.username.len() as u16;

// Convert to buffers.
let mut ver_str_len_buf = u16::encode::<u16>(&ver_str_len).unwrap();
let mut ver_str_buf = Vec::from(env!("CARGO_PKG_VERSION").as_bytes());
let mut name_str_len_buf = u16::encode::<u16>(&name_str_len).unwrap();
let mut net_protocol_version_buf = u64::encode::<u64>(&net_protocol_version).unwrap();
let mut name_str_buf = Vec::from(self.user_info.username.as_bytes());

// Move all buffers to one big buffer.
let mut out_buffer: Vec<u8> = Vec::new();
out_buffer.append(&mut ver_str_len_buf);
out_buffer.append(&mut ver_str_buf);
out_buffer.append(&mut data_id_buf);
out_buffer.append(&mut net_protocol_version_buf);
out_buffer.append(&mut name_str_len_buf);
out_buffer.append(&mut name_str_buf);

Expand Down Expand Up @@ -848,23 +871,10 @@ impl UserTcpService {
return ConnectResult::SleepWithErr(PASSWORD_RETRY_DELAY_SEC);
}
Some(ConnectServerAnswer::WrongVersion) => {
// Get correct version string (get size first).
loop {
match self.read_from_socket(&mut in_buf) {
IoResult::WouldBlock => {
thread::sleep(Duration::from_millis(INTERVAL_TCP_MESSAGE_MS));
continue;
}
IoResult::Ok(_bytes) => break,
res => return ConnectResult::IoErr(res),
}
}
let required_ver_str_size = u16::decode::<u16>(&in_buf).unwrap();

// Get correct version string.
let mut required_ver_str_buf = vec![0u8; required_ver_str_size as usize];
// Get correct version.
let mut required_ver_buf = vec![0u8; std::mem::size_of::<u64>()];
loop {
match self.read_from_socket(&mut required_ver_str_buf) {
match self.read_from_socket(&mut required_ver_buf) {
IoResult::WouldBlock => {
thread::sleep(Duration::from_millis(INTERVAL_TCP_MESSAGE_MS));
continue;
Expand All @@ -873,15 +883,13 @@ impl UserTcpService {
res => return ConnectResult::IoErr(res),
}
}
let ver_str = std::str::from_utf8(&required_ver_str_buf);
let ver_str = u64::decode::<u64>(&required_ver_buf);
if let Err(e) = ver_str {
return ConnectResult::Err(
format!("std::str::from_utf8() failed, error: failed to convert on 'required_ver_str_buf' (error: {}) at [{}, {}]",
format!("u64::decode::<u64>() failed, error: failed to convert on 'required_ver_str_buf' (error: {}) at [{}, {}]",
e, file!(), line!()));
}
return ConnectResult::WrongVersion(
String::from(std::str::from_utf8(&required_ver_str_buf).unwrap()).clone(),
);
return ConnectResult::WrongProtocol(ver_str.unwrap());
}
Some(ConnectServerAnswer::UsernameTaken) => return ConnectResult::UsernameTaken,
None => {
Expand Down

0 comments on commit e72df1b

Please sign in to comment.