Unmodified copy of the tsclientlib workspace crates (MIT OR Apache-2.0)
with the tsdeclarations submodule (83cb8a9) flattened into plain files.
See crates/proto/UPSTREAM.md for the path mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 12:46:11 +00:00
commit 7b6959c4cc
119 files changed
+24322

No files matched your search

@@ -0,0 +1,66 @@
use anyhow::Result;
use clap::Parser;
use tokio::sync::mpsc;
use tokio::task::LocalSet;
use tracing::{debug, info};
use tsclientlib::ClientId;
use tsproto_packets::packets::{Direction, InAudioBuf};
mod audio_utils;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct ConnectionId(u64);
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The volume for the capturing
#[arg(default_value_t = 1.0)]
volume: f32,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_id = ConnectionId(0);
let local_set = LocalSet::new();
let audiodata = audio_utils::start(&local_set)?;
let (send, mut recv) = mpsc::channel(1);
{
let mut a2t = audiodata.a2ts.lock().unwrap();
a2t.set_listener(send);
a2t.set_volume(args.volume);
a2t.set_playing(true);
}
let t2a = audiodata.ts2a.clone();
loop {
// Wait for ctrl + c
tokio::select! {
send_audio = recv.recv() => {
if let Some(packet) = send_audio {
let from = ClientId(0);
let mut t2a = t2a.lock().unwrap();
let in_audio = InAudioBuf::try_new(Direction::C2S, packet.into_vec()).unwrap();
if let Err(error) = t2a.play_packet((con_id, from), in_audio) {
debug!(%error, "Failed to play packet");
}
} else {
info!("Audio sending stream was canceled");
break;
}
}
_ = tokio::signal::ctrl_c() => { break; }
};
}
Ok(())
}
+127
View File
@@ -0,0 +1,127 @@
//! This example connects to a teamspeak instance and joins a channel.
//! The connected bot-identity will listen on your microphone and send everything to the current
//! channel. In parallel, the program will play back all other clients in the channel via its own
//! audio output.
//! Microphone -> Channel
//! Channel -> PC Speakers
use anyhow::{bail, Result};
use clap::Parser;
use futures::prelude::*;
use tokio::sync::mpsc;
use tokio::task::LocalSet;
use tracing::{debug, info};
use tsclientlib::{ClientId, Connection, DisconnectOptions, Identity, StreamItem};
use tsproto_packets::packets::AudioData;
mod audio_utils;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct ConnectionId(u64);
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// The volume for the capturing
#[arg(default_value_t = 1.0)]
volume: f32,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_id = ConnectionId(0);
let local_set = LocalSet::new();
let audiodata = audio_utils::start(&local_set)?;
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
let (send, mut recv) = mpsc::channel(5);
{
let mut a2t = audiodata.a2ts.lock().unwrap();
a2t.set_listener(send);
a2t.set_volume(args.volume);
a2t.set_playing(true);
}
loop {
let t2a = audiodata.ts2a.clone();
let events = con.events().try_for_each(|e| async {
if let StreamItem::Audio(packet) = e {
let from = ClientId(match packet.data().data() {
AudioData::S2C { from, .. } => *from,
AudioData::S2CWhisper { from, .. } => *from,
_ => panic!("Can only handle S2C packets but got a C2S packet"),
});
let mut t2a = t2a.lock().unwrap();
if let Err(error) = t2a.play_packet((con_id, from), packet) {
debug!(%error, "Failed to play packet");
}
}
Ok(())
});
// Wait for ctrl + c
tokio::select! {
send_audio = recv.recv() => {
if let Some(packet) = send_audio {
con.send_audio(packet)?;
} else {
info!("Audio sending stream was canceled");
break;
}
}
_ = tokio::signal::ctrl_c() => { break; }
r = events => {
r?;
bail!("Disconnected");
}
};
}
// Disconnect
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
Ok(())
}
@@ -0,0 +1,184 @@
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use anyhow::{Result, format_err};
use audiopus::coder::Encoder;
use cpal::traits::{DeviceTrait, StreamTrait};
use cpal::{Device, Stream, StreamConfig};
use futures::prelude::*;
use tokio::sync::mpsc;
use tokio::task::LocalSet;
use tokio::time::{self, Duration};
use tokio_stream::wrappers::IntervalStream;
use tracing::{debug, error, instrument, warn};
use tsproto_packets::packets::{AudioData, CodecType, OutAudio, OutPacket};
use super::*;
pub struct AudioToTs {
device: Device,
listener: Arc<Mutex<Option<mpsc::Sender<OutPacket>>>>,
stream: Option<Stream>,
is_playing: bool,
/// Storing an f32
volume: Arc<AtomicU32>,
}
struct Callback {
listener: Arc<Mutex<Option<mpsc::Sender<OutPacket>>>>,
encoder: Encoder,
/// Storing an f32
volume: Arc<AtomicU32>,
tmp_buffer: [f32; USUAL_FRAME_SIZE * 2],
opus_output: [u8; MAX_OPUS_FRAME_SIZE],
}
impl AudioToTs {
pub fn new(device: Device, local_set: &LocalSet) -> Result<Arc<Mutex<Self>>> {
let listener = Arc::new(Mutex::new(Default::default()));
let volume = Arc::new(AtomicU32::new(1.0_f32.to_bits()));
let res = Arc::new(Mutex::new(Self {
device,
listener,
stream: None,
is_playing: false,
volume,
}));
Self::start(res.clone(), local_set);
Ok(res)
}
#[instrument(skip(self))]
fn open_capture(&self) -> Result<Stream> {
let config = StreamConfig {
channels: 1,
sample_rate: 48000,
buffer_size: cpal::BufferSize::Fixed(USUAL_FRAME_SIZE as u32),
};
let encoder = Encoder::new(
audiopus::SampleRate::Hz48000,
audiopus::Channels::Mono,
audiopus::Application::Voip,
)
.expect("Could not create encoder");
let mut callback = Callback {
listener: self.listener.clone(),
encoder,
volume: self.volume.clone(),
tmp_buffer: [0.0; _],
opus_output: [0; _],
};
self.device
.build_input_stream(
config,
move |audio_data, _| callback.callback(audio_data),
|error| error!(%error, "Error during audio capture"),
Some(Duration::from_secs(5)),
)
.map_err(|e| format_err!("cpal error: {}", e))
}
pub fn set_listener(&self, sender: mpsc::Sender<OutPacket>) {
let mut listener = self.listener.lock().unwrap();
*listener = Some(sender);
}
pub fn set_volume(&mut self, volume: f32) {
self.volume.store(volume.to_bits(), Ordering::Relaxed);
}
pub fn set_playing(&mut self, playing: bool) {
if let Some(stream) = &self.stream {
if playing {
if let Err(error) = stream.play() {
error!(%error, "Failed to start stream");
self.stream = None;
} else {
self.is_playing = true;
}
} else {
if let Err(error) = stream.pause() {
error!(%error, "Failed to pause stream");
self.stream = None;
}
self.is_playing = false;
}
}
}
#[instrument(skip(a2t, local_set))]
fn start(a2t: Arc<Mutex<Self>>, local_set: &LocalSet) {
local_set.spawn_local(
IntervalStream::new(time::interval(Duration::from_secs(1))).for_each(move |_| {
let mut a2t = a2t.lock().unwrap();
if a2t.stream.is_none() {
// Try to reconnect to audio
match a2t.open_capture() {
Ok(s) => {
a2t.stream = Some(s);
debug!("Reconnected to capture device");
if a2t.is_playing {
a2t.set_playing(true);
}
}
Err(error) => {
error!(%error, "Failed to open capture device");
}
};
}
future::ready(())
}),
);
}
}
impl Callback {
#[instrument(skip(self, buffer))]
fn callback<'a>(&'a mut self, mut buffer: &'a [f32]) {
// Handle volume
let volume = f32::from_bits(self.volume.load(Ordering::Relaxed));
if volume != 1.0 {
if self.tmp_buffer.len() < buffer.len() {
warn!("tmp buffer len smaller than received capture buffer, dropping data");
}
for (dst, src) in self.tmp_buffer.iter_mut().zip(buffer.iter()) {
*dst = *src * volume;
}
buffer = &self.tmp_buffer[..buffer.len()];
}
match self.encoder.encode_float(buffer, &mut self.opus_output[..]) {
Err(error) => {
error!(%error, "Failed to encode opus");
}
Ok(len) => {
// Create packet
let packet = OutAudio::new(&AudioData::C2S {
id: 0,
codec: CodecType::OpusVoice,
data: &self.opus_output[..len],
});
// Write into packet sink
let mut listener = self.listener.lock().unwrap();
if let Some(lis) = &mut *listener {
match lis.try_send(packet) {
Err(mpsc::error::TrySendError::Closed(_)) => *listener = None,
_ => {}
}
}
}
}
}
}
@@ -0,0 +1,37 @@
use std::sync::{Arc, Mutex};
use anyhow::Result;
use cpal::traits::HostTrait;
use tokio::task::LocalSet;
use audio_to_ts::AudioToTs;
use ts_to_audio::TsToAudio;
pub mod audio_to_ts;
pub mod ts_to_audio;
/// The usual frame size.
///
/// Use 48 kHz, 20 ms frames (50 per second) and mono data (1 channel).
/// This means 1920 samples and 7.5 kiB.
const USUAL_FRAME_SIZE: usize = 48000 / 50;
/// The maximum size of an opus frame is 1275 as from RFC6716.
const MAX_OPUS_FRAME_SIZE: usize = 1275;
#[derive(Clone)]
pub struct AudioData {
pub a2ts: Arc<Mutex<AudioToTs>>,
pub ts2a: Arc<Mutex<TsToAudio>>,
}
pub(crate) fn start(local_set: &LocalSet) -> Result<AudioData> {
let host = cpal::default_host();
let output_device = host.default_output_device().unwrap();
let input_device = host.default_input_device().unwrap();
let ts2a = TsToAudio::new(output_device, local_set)?;
let a2ts = AudioToTs::new(input_device, local_set)?;
Ok(AudioData { a2ts, ts2a })
}
@@ -0,0 +1,138 @@
use std::sync::{Arc, Mutex};
use anyhow::{Result, format_err};
use cpal::traits::{DeviceTrait, StreamTrait};
use cpal::{Device, Stream, StreamConfig};
use futures::prelude::*;
use tokio::task::LocalSet;
use tokio::time::{self, Duration};
use tokio_stream::wrappers::IntervalStream;
use tracing::{debug, error, instrument};
use tsclientlib::ClientId;
use tsproto_packets::packets::InAudioBuf;
use super::*;
use crate::ConnectionId;
type Id = (ConnectionId, ClientId);
type AudioHandler = tsclientlib::audio::AudioHandler<Id>;
pub struct TsToAudio {
device: Device,
stream: Option<Stream>,
is_playing: bool,
data: Arc<Mutex<AudioHandler>>,
}
struct Callback {
data: Arc<Mutex<AudioHandler>>,
}
impl TsToAudio {
pub fn new(device: Device, local_set: &LocalSet) -> Result<Arc<Mutex<Self>>> {
let data = Arc::new(Mutex::new(AudioHandler::new()));
let res = Arc::new(Mutex::new(Self { device, stream: None, is_playing: false, data }));
Self::start(res.clone(), local_set);
Ok(res)
}
#[instrument(skip(self))]
fn open_playback(&self) -> Result<Stream> {
let config = StreamConfig {
channels: 2,
sample_rate: 48000,
buffer_size: cpal::BufferSize::Fixed(USUAL_FRAME_SIZE as u32),
};
let mut callback = Callback { data: self.data.clone() };
self.device
.build_output_stream(
config,
move |audio_data, _| callback.callback(audio_data),
|error| error!(%error, "Error during audio playback"),
Some(Duration::from_secs(5)),
)
.map_err(|e| format_err!("cpal error: {}", e))
}
#[instrument(skip(t2a, local_set))]
fn start(t2a: Arc<Mutex<Self>>, local_set: &LocalSet) {
local_set.spawn_local(
IntervalStream::new(time::interval(Duration::from_secs(1))).for_each(move |_| {
let mut t2a = t2a.lock().unwrap();
if t2a.stream.is_none() {
// Try to reconnect to audio
match t2a.open_playback() {
Ok(s) => {
t2a.stream = Some(s);
t2a.is_playing = false;
debug!("Reconnected to playback device");
}
Err(error) => {
error!(%error, "Failed to open playback device");
}
};
}
if let Some(stream) = &t2a.stream {
let data_empty = t2a.data.lock().unwrap().get_queues().is_empty();
if !t2a.is_playing && !data_empty {
debug!("Resuming playback");
if let Err(error) = stream.play() {
error!(%error, "Failed to start stream");
t2a.stream = None;
} else {
t2a.is_playing = true;
}
} else if t2a.is_playing && data_empty {
debug!("Pausing playback");
if let Err(error) = stream.pause() {
error!(%error, "Failed to pause stream");
t2a.stream = None;
}
t2a.is_playing = false;
}
}
future::ready(())
}),
);
}
#[instrument(skip(self, id, packet))]
pub(crate) fn play_packet(&mut self, id: Id, packet: InAudioBuf) -> Result<()> {
{
let mut data = self.data.lock().unwrap();
data.handle_packet(id, packet)?;
}
if !self.is_playing {
if let Some(stream) = &self.stream {
debug!("Resuming playback");
if let Err(error) = stream.play() {
error!(%error, "Failed to start stream");
self.stream = None;
} else {
self.is_playing = true;
}
}
}
Ok(())
}
}
impl Callback {
fn callback(&mut self, buffer: &mut [f32]) {
// Clear buffer
for d in &mut *buffer {
*d = 0.0;
}
let mut data = self.data.lock().unwrap();
data.fill_buffer(buffer);
}
}
@@ -0,0 +1,129 @@
use anyhow::{bail, Result};
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::data::{self, Channel, Client};
use tsclientlib::prelude::*;
use tsclientlib::{ChannelId, Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
/// `channels` have to be ordered.
fn print_channels(clients: &[&Client], channels: &[&Channel], parent: ChannelId, depth: usize) {
let indention = " ".repeat(depth);
for channel in channels {
if channel.parent == parent {
println!("{}- {}", indention, channel.name);
// Print all clients in this channel
for client in clients {
if client.channel == channel.id {
println!("{} {}", indention, client.name);
}
}
print_channels(clients, channels, channel.id, depth + 1);
}
}
}
fn print_channel_tree(con: &data::Connection) {
let mut channels: Vec<_> = con.channels.values().collect();
let mut clients: Vec<_> = con.clients.values().collect();
// This is not the real sorting order, the order is the ChannelId of the
// channel on top of this one, but we don't care for this example.
channels.sort_by_key(|ch| ch.order.0);
clients.sort_by_key(|c| c.talk_power);
println!("{}", con.server.name);
print_channels(&clients, &channels, ChannelId(0), 0);
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
con.get_state().unwrap().server.set_subscribed(true).send(&mut con)?;
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(1)) => {}
_ = events.next() => {
bail!("Disconnected");
}
};
drop(events);
// Print channel tree
print_channel_tree(con.get_state().unwrap());
// Change name
{
let state = con.get_state().unwrap();
let name = state.clients[&state.own_client].name.clone();
state
.client_update()
.set_input_muted(true)
.set_name(&format!("{}1", name))
.send(&mut con)?;
}
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(3)) => {}
_ = events.next() => {
bail!("Disconnected");
}
};
drop(events);
// Disconnect
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
Ok(())
}
+86
View File
@@ -0,0 +1,86 @@
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tracing::error;
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
/// How many connections
#[arg()]
count: usize,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address.as_str())
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
stream::iter(0..args.count)
.for_each_concurrent(None, |_| {
let con_config = con_config.clone();
tokio::spawn(async move {
// Connect
let mut con = con_config.connect().unwrap();
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(Err(error)) = r {
error!(%error, "Connection failed");
return;
}
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(15)) => {}
_ = events.next() => {
error!("Disconnected unexpectedly");
return;
}
};
drop(events);
// Disconnect
let _ = con.disconnect(DisconnectOptions::new());
con.events().for_each(|_| future::ready(())).await;
})
.map(|_| ())
})
.await;
Ok(())
}
@@ -0,0 +1,78 @@
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::sync::SyncConnection;
use tsclientlib::{Connection, DisconnectOptions, Identity};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let con: SyncConnection = con_config.connect()?.into();
let mut handle = con.get_handle();
// Do event handling in another thread
tokio::spawn(con.for_each(|_| future::ready(())));
handle.wait_until_connected().await?;
let welcome_message = handle
.with_connection(|con| Result::<_>::Ok(con.get_state()?.server.welcome_message.clone()))
.await??;
println!("Server welcome message: {}", sanitize(&welcome_message));
// Wait some time
time::sleep(Duration::from_secs(1)).await;
// Disconnect
handle.disconnect(DisconnectOptions::new()).await?;
Ok(())
}
/// Only retain a certain set of characters.
fn sanitize(s: &str) -> String {
s.chars()
.filter(|c| {
c.is_alphanumeric()
|| [' ', '\t', '.', ':', '-', '_', '"', '\'', '/', '(', ')', '[', ']', '{', '}']
.contains(c)
})
.collect()
}
@@ -0,0 +1,85 @@
use anyhow::{bail, Result};
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
println!("Server welcome message: {}", sanitize(&con.get_state()?.server.welcome_message));
// Wait some time
let mut events = con.events().try_filter(|_| future::ready(false));
tokio::select! {
_ = time::sleep(Duration::from_secs(1)) => {}
_ = events.next() => {
bail!("Disconnected");
}
};
drop(events);
// Disconnect
con.disconnect(DisconnectOptions::new())?;
con.events().for_each(|_| future::ready(())).await;
Ok(())
}
/// Only retain a certain set of characters.
fn sanitize(s: &str) -> String {
s.chars()
.filter(|c| {
c.is_alphanumeric()
|| [' ', '\t', '.', ':', '-', '_', '"', '\'', '/', '(', ')', '[', ']', '{', '}']
.contains(c)
})
.collect()
}
+77
View File
@@ -0,0 +1,77 @@
use anyhow::Result;
use clap::Parser;
use futures::prelude::*;
use tokio::time::{self, Duration};
use tsclientlib::prelude::*;
use tsclientlib::sync::SyncConnection;
use tsclientlib::{Connection, DisconnectOptions, Identity, StreamItem};
#[derive(Parser, Debug)]
#[command(author, about)]
struct Args {
/// The address of the server to connect to
#[arg(short, long, default_value = "localhost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn real_main() -> Result<()> {
tracing_subscriber::fmt::init();
// Parse command line options
let args = Args::parse();
let con_config = Connection::build(args.address)
.log_commands(args.verbose >= 1)
.log_packets(args.verbose >= 2)
.log_udp_packets(args.verbose >= 3);
// Optionally set the key of this client, otherwise a new key is generated.
let id = Identity::new_from_str(
"MG0DAgeAAgEgAiAIXJBlj1hQbaH0Eq0DuLlCmH8bl+veTAO2+\
k9EQjEYSgIgNnImcmKo7ls5mExb6skfK2Tw+u54aeDr0OP1ITs\
C/50CIA8M5nmDBnmDM/gZ//4AAAAAAAAAAAAAAAAAAAAZRzOI").unwrap();
let con_config = con_config.identity(id);
// Connect
let mut con = con_config.connect()?;
let r = con
.events()
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
.next()
.await;
if let Some(r) = r {
r?;
}
let sync_con: SyncConnection = con.into();
let mut con = sync_con.get_handle();
tokio::spawn(sync_con.for_each(|_| future::ready(())));
con.with_connection(move |mut con| {
let state = con.get_state()?;
state.server.send_textmessage("Hello there").send(&mut con)?;
Result::<_>::Ok(())
})
.await??;
// Wait some time
time::sleep(Duration::from_secs(1)).await;
// Disconnect
con.disconnect(DisconnectOptions::new()).await?;
Ok(())
}