Sponge
CS144's user-space TCP library
socket_example_2.cc
Go to the documentation of this file.
1 const uint16_t portnum = ((std::random_device()()) % 50000) + 1025;
2 
3 // create a TCP socket, bind it to a local address, and listen
5 sock1.bind(Address("127.0.0.1", portnum));
6 sock1.listen(1);
7 
8 // create another socket and connect to the first one
10 sock2.connect(Address("127.0.0.1", portnum));
11 
12 // accept the connection
13 auto sock3 = sock1.accept();
14 sock3.write("hi there");
15 
16 auto recvd = sock2.read();
17 sock2.write("hi yourself");
18 
19 auto recvd2 = sock3.read();
20 
21 sock1.close(); // don't need to accept any more connections
22 sock2.close(); // you can call close(2) on a socket
23 sock3.shutdown(SHUT_RDWR); // you can also shutdown(2) a socket
24 if (recvd != "hi there" || recvd2 != "hi yourself") {
25  throw std::runtime_error("wrong data received");
26 }
portnum
const uint16_t portnum
Definition: socket_example_2.cc:1
TCPSocket::accept
TCPSocket accept()
Accept a new incoming connection.
Definition: socket.cc:151
TCPSocket
A wrapper around TCP sockets.
Definition: socket.hh:88
recvd2
auto recvd2
Definition: socket_example_2.cc:19
FileDescriptor::write
size_t write(const char *str, const bool write_all=true)
Write a string, possibly blocking until all is written.
Definition: file_descriptor.hh:65
sock3
auto sock3
Definition: socket_example_2.cc:13
FileDescriptor::close
void close()
Close the underlying file descriptor.
Definition: file_descriptor.hh:74
FileDescriptor::read
std::string read(const size_t limit=std::numeric_limits< size_t >::max())
Read up to limit bytes.
Address
Wrapper around IPv4 addresses and DNS operations.
Definition: address.hh:13
std::random_device
sock2
TCPSocket sock2
Definition: socket_example_2.cc:9
Socket::bind
void bind(const Address &address)
Bind a socket to a specified address with bind(2), usually for listen/accept.
Definition: socket.cc:61
TCPSocket::listen
void listen(const int backlog=16)
Mark a socket as listening for incoming connections.
Definition: socket.cc:146
std::runtime_error
Socket::connect
void connect(const Address &address)
Connect a socket to a specified peer address with connect(2).
Definition: socket.cc:65
sock1
TCPSocket sock1
Definition: socket_example_2.cc:4
recvd
auto recvd
Definition: socket_example_2.cc:16