1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use rich_sdl2_rust::{Result, Sdl, SdlError};
use std::{ffi::CString, marker::PhantomData, mem::MaybeUninit, net::Ipv4Addr, ptr::NonNull};
use crate::{bind, conn::TcpConnection, sock::UdpSocket, Net};
pub struct NetClient<'net> {
address: bind::IPaddress,
_phantom: PhantomData<&'net Net<'net>>,
}
impl<'net> NetClient<'net> {
pub fn new(_net: &'net Net<'net>, address: Ipv4Addr, port: Option<u16>) -> Result<Self> {
let address_cstr = CString::new(address.to_string()).unwrap();
let mut address = MaybeUninit::uninit();
let ret = unsafe {
bind::SDLNet_ResolveHost(
address.as_mut_ptr(),
address_cstr.as_ptr(),
port.unwrap_or(0),
)
};
if ret != 0 {
Err(SdlError::Others { msg: Sdl::error() })
} else {
let address = unsafe { address.assume_init() };
Ok(Self {
address,
_phantom: PhantomData,
})
}
}
pub fn with_hostname(_net: &'net Net<'net>, hostname: &str, port: Option<u16>) -> Result<Self> {
let hostname_cstr = CString::new(hostname).unwrap();
let mut address = MaybeUninit::uninit();
let ret = unsafe {
bind::SDLNet_ResolveHost(
address.as_mut_ptr(),
hostname_cstr.as_ptr(),
port.unwrap_or(0),
)
};
if ret != 0 {
Err(SdlError::Others { msg: Sdl::error() })
} else {
let address = unsafe { address.assume_init() };
Ok(Self {
address,
_phantom: PhantomData,
})
}
}
pub fn open_tcp(&mut self) -> Option<TcpConnection> {
let opponent = unsafe { bind::SDLNet_TCP_Open(&mut self.address as *mut _) };
NonNull::new(opponent).map(TcpConnection::new)
}
pub fn open_udp(&mut self) -> Result<UdpSocket> {
UdpSocket::new(self.address.port)
}
}