dsfml.network.tcpsocket

TCP is a connected protocol, which means that a TCP socket can only communicate with the host it is connected to.

It can't send or receive anything if it is not connected.

The TCP protocol is reliable but adds a slight overhead. It ensures that your data will always be received in order and without errors (no data corrupted, lost or duplicated).

When a socket is connected to a remote host, you can retrieve informations about this host with the getRemoteAddress and getRemotePort functions.

You can also get the local port to which the socket is bound (which is automatically chosen when the socket is connected), with the getLocalPort function.

Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, and cannot ensure that one call to Send will exactly match one call to Receive at the other end of the socket.

The high-level interface uses packets (see $(PACKET_LINK)), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the $(PACKET_LINK) class to get more details about how they work.

The socket is automatically disconnected when it is destroyed, but if you want to explicitely close the connection while the socket instance is still alive, you can call disconnect.

Members

Classes

TcpSocket
class TcpSocket

Specialized socket using the TCP protocol.

Examples

1 // ----- The client -----
2 
3 // Create a socket and connect it to 192.168.1.50 on port 55001
4 auto socket = new TcpSocket();
5 socket.connect("192.168.1.50", 55001);
6 
7 // Send a message to the connected host
8 string message = "Hi, I am a client";
9 socket.send(message);
10 
11 // Receive an answer from the server
12 char[1024] buffer;
13 size_t received = 0;
14 socket.receive(buffer, received);
15 writeln("The server said: ", buffer[0 .. received]);
16 
17 // ----- The server -----
18 
19 // Create a listener to wait for incoming connections on port 55001
20 auto listener = TcpListener();
21 listener.listen(55001);
22 
23 // Wait for a connection
24 auto socket = new TcpSocket();
25 listener.accept(socket);
26 writeln("New client connected: ", socket.getRemoteAddress());
27 
28 // Receive a message from the client
29 char[1024] buffer;
30 size_t received = 0;
31 socket.receive(buffer, received);
32 writeln("The client said: ", buffer[0 .. received]);
33 
34 // Send an answer
35 string message = "Welcome, client";
36 socket.send(message);

See Also

$(SOCKET_LINK), $(UDPSOCKET_LINK), $(PACKET_LINK)

Meta