Skip to content

Commit

Permalink
Implement fmt::Write for TcpSocket.
Browse files Browse the repository at this point in the history
whitequark committed Jul 30, 2017
1 parent ee0b8b3 commit 6bc6cc7
Showing 3 changed files with 19 additions and 9 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -200,9 +200,9 @@ It responds to:

* pings (`ping 192.168.69.1`);
* UDP packets on port 6969 (`socat stdio udp4-connect:192.168.69.1:6969 <<<"abcdefg"`),
where it will respond "yo dawg" to any incoming packet;
where it will respond "hello" to any incoming packet;
* TCP packets on port 6969 (`socat stdio tcp4-connect:192.168.69.1:6969`),
where it will respond "yo dawg" to any incoming connection and immediately close it;
where it will respond "hello" to any incoming connection and immediately close it;
* TCP packets on port 6970 (`socat stdio tcp4-connect:192.168.69.1:6970 <<<"abcdefg"`),
where it will respond with reversed chunks of the input indefinitely.
* TCP packets on port 6971 (`cat /dev/urandom | socat stdio tcp4-connect:192.168.69.1:6971`),
13 changes: 6 additions & 7 deletions examples/server.rs
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ extern crate smoltcp;
mod utils;

use std::str;
use std::fmt::Write;
use std::time::Instant;
use smoltcp::Error;
use smoltcp::wire::{EthernetAddress, IpAddress};
@@ -60,7 +61,7 @@ fn main() {

let mut tcp_6970_active = false;
loop {
// udp:6969: respond "yo dawg"
// udp:6969: respond "hello"
{
let socket: &mut UdpSocket = sockets.get_mut(udp_handle).as_socket();
if !socket.is_open() {
@@ -76,25 +77,23 @@ fn main() {
Err(_) => None
};
if let Some(endpoint) = client {
let data = b"yo dawg\n";
let data = b"hello\n";
debug!("udp:6969 send data: {:?}",
str::from_utf8(data.as_ref()).unwrap());
socket.send_slice(data, endpoint).unwrap();
}
}

// tcp:6969: respond "yo dawg"
// tcp:6969: respond "hello"
{
let socket: &mut TcpSocket = sockets.get_mut(tcp1_handle).as_socket();
if !socket.is_open() {
socket.listen(6969).unwrap();
}

if socket.can_send() {
let data = b"yo dawg\n";
debug!("tcp:6969 send data: {:?}",
str::from_utf8(data.as_ref()).unwrap());
socket.send_slice(data).unwrap();
debug!("tcp:6969 send greeting");
write!(socket, "hello\n");
debug!("tcp:6969 close");
socket.close();
}
11 changes: 11 additions & 0 deletions src/socket/tcp.rs
Original file line number Diff line number Diff line change
@@ -1182,6 +1182,17 @@ impl<'a> TcpSocket<'a> {
}
}

impl<'a> fmt::Write for TcpSocket<'a> {
fn write_str(&mut self, slice: &str) -> fmt::Result {
let slice = slice.as_bytes();
if self.send_slice(slice) == Ok(slice.len()) {
Ok(())
} else {
Err(fmt::Error)
}
}
}

impl<'a> IpPayload for TcpRepr<'a> {
fn buffer_len(&self) -> usize {
self.buffer_len()

0 comments on commit 6bc6cc7

Please sign in to comment.