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));
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 }
Wrapper around IPv4 addresses and DNS operations.
Definition: address.hh:13
void close()
Close the underlying file descriptor.
size_t write(const char *str, const bool write_all=true)
Write a string, possibly blocking until all is written.
std::string read(const size_t limit=std::numeric_limits< size_t >::max())
Read up to limit bytes.
void connect(const Address &address)
Connect a socket to a specified peer address with connect(2).
Definition: socket.cc:65
void bind(const Address &address)
Bind a socket to a specified address with bind(2), usually for listen/accept.
Definition: socket.cc:61
A wrapper around TCP sockets.
Definition: socket.hh:88
TCPSocket accept()
Accept a new incoming connection.
Definition: socket.cc:151
void listen(const int backlog=16)
Mark a socket as listening for incoming connections.
Definition: socket.cc:146
const uint16_t portnum
TCPSocket sock2
auto recvd2
TCPSocket sock1
auto sock3
auto recvd