1 /* 2 DSFML - The Simple and Fast Multimedia Library for D 3 4 Copyright (c) 2013 - 2015 Jeremy DeHaan (dehaan.jeremiah@gmail.com) 5 6 This software is provided 'as-is', without any express or implied warranty. 7 In no event will the authors be held liable for any damages arising from the use of this software. 8 9 Permission is granted to anyone to use this software for any purpose, including commercial applications, 10 and to alter it and redistribute it freely, subject to the following restrictions: 11 12 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. 13 If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 14 15 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 16 17 3. This notice may not be removed or altered from any source distribution 18 */ 19 20 ///A module containing the TcpSocket class. 21 module dsfml.network.tcpsocket; 22 23 import core.time; 24 25 import dsfml.network.socket; 26 import dsfml.network.ipaddress; 27 import dsfml.network.packet; 28 29 import dsfml.system.err; 30 31 /** 32 *Specialized socket using the TCP protocol. 33 * 34 *TCP is a connected protocol, which means that a TCP socket can only communicate with the host it is connected to. 35 * 36 *It can't send or receive anything if it is not connected. 37 * 38 *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). 39 * 40 *When a socket is connected to a remote host, you can retrieve informations about this host with the getRemoteAddress and getRemotePort functions. 41 *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. 42 * 43 *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. 44 * 45 *The high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work. 46 * 47 *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. 48 */ 49 class TcpSocket:Socket 50 { 51 package sfTcpSocket* sfPtr; 52 53 ///Default constructor 54 this() 55 { 56 sfPtr = sfTcpSocket_create(); 57 } 58 59 ///Destructor 60 ~this() 61 { 62 import dsfml.system.config; 63 mixin(destructorOutput); 64 sfTcpSocket_destroy(sfPtr); 65 } 66 67 ///Get the port to which the socket is bound locally. 68 /// 69 ///If the socket is not connected, this function returns 0. 70 /// 71 ///Returns: Port to which the socket is bound. 72 ushort getLocalPort() 73 { 74 return sfTcpSocket_getLocalPort(sfPtr); 75 } 76 77 ///Get the address of the connected peer. 78 /// 79 ///It the socket is not connected, this function returns IpAddress.None. 80 /// 81 ///Returns: Address of the remote peer. 82 IpAddress getRemoteAddress() 83 { 84 IpAddress temp; 85 86 sfTcpSocket_getRemoteAddress(sfPtr,temp.m_address.ptr); 87 88 return temp; 89 } 90 91 ///Get the port of the connected peer to which the socket is connected. 92 /// 93 ///If the socket is not connected, this function returns 0. 94 /// 95 ///Returns: Remote port to which the socket is connected. 96 ushort getRemotePort() 97 { 98 return sfTcpSocket_getRemotePort(sfPtr); 99 } 100 101 ///Set the blocking state of the socket. 102 /// 103 ///In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. 104 ///In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking. 105 /// 106 ///Params: 107 /// blocking = True to set the socket as blocking, false for non-blocking. 108 void setBlocking(bool blocking) 109 { 110 sfTcpSocket_setBlocking(sfPtr, blocking); 111 } 112 113 ///Connect the socket to a remote peer. 114 /// 115 ///In blocking mode, this function may take a while, especially if the remote peer is not reachable. The last parameter allows you to stop trying to connect after a given timeout. 116 ///If the socket was previously connected, it is first disconnected. 117 /// 118 ///Params: 119 /// host = Address of the remote peer. 120 /// port = Port of the remote peer. 121 /// timeout = Optional maximum time to wait. 122 /// 123 ///Returns: Status code. 124 Status connect(IpAddress host, ushort port, Duration timeout = Duration.zero()) 125 { 126 return sfTcpSocket_connect(sfPtr, host.m_address.ptr,port, timeout.total!"usecs"); 127 } 128 129 ///Disconnect the socket from its remote peer. 130 /// 131 ///This function gracefully closes the connection. If the socket is not connected, this function has no effect. 132 void disconnect() 133 { 134 sfTcpSocket_disconnect(sfPtr); 135 } 136 137 ///Tell whether the socket is in blocking or non-blocking mode. 138 /// 139 ///Returns: True if the socket is blocking, false otherwise. 140 bool isBlocking() 141 { 142 return (sfTcpSocket_isBlocking(sfPtr)); 143 } 144 145 ///Send raw data to the remote peer. 146 /// 147 ///This function will fail if the socket is not connected. 148 /// 149 ///Params: 150 /// data = Sequence of bytes to send. 151 /// 152 ///Returns: Status code. 153 Status send(const(void)[] data) 154 { 155 import dsfml.system..string; 156 157 Status toReturn = sfTcpSocket_send(sfPtr, data.ptr, data.length); 158 err.write(dsfml.system..string.toString(sfErr_getOutput())); 159 return toReturn; 160 } 161 162 ///Send a formatted packet of data to the remote peer. 163 /// 164 ///This function will fail if the socket is not connected. 165 /// 166 ///Params: 167 /// packet = Packet to send. 168 /// 169 ///Returns: Status code. 170 Status send(Packet packet) 171 { 172 import std.stdio; 173 //temporary packet to be removed on function exit 174 scope SfPacket temp = new SfPacket(); 175 176 //getting packet's "to send" data 177 temp.append(packet.onSend()); 178 179 //send the data 180 return sfTcpSocket_sendPacket(sfPtr, temp.sfPtr); 181 } 182 ///Receive raw data from the remote peer. 183 /// 184 ///In blocking mode, this function will wait until some bytes are actually received. This function will fail if the socket is not connected. 185 /// 186 ///Params: 187 /// data = Array to fill with the received bytes. 188 /// sizeReceived = This variable is filled with the actual number of bytes received. 189 /// 190 ///Returns: Status code. 191 Status receive(void[] data , out size_t sizeReceived) 192 { 193 //This is terrible and will be fixed in 2.2 194 195 Status status; 196 197 void* temp = sfTcpSocket_receive(sfPtr, data.length, &sizeReceived, &status); 198 199 data[0..sizeReceived] = temp[0..sizeReceived].dup; 200 201 return status; 202 } 203 204 //Receive a formatted packet of data from the remote peer. 205 /// 206 ///In blocking mode, this function will wait until the whole packet has been received. This function will fail if the socket is not connected. 207 /// 208 ///Params: 209 /// packet = Packet to fill with the received data. 210 /// 211 ///Returns: Status code. 212 Status receive(Packet packet) 213 { 214 //temporary packet to be removed on function exit 215 scope SfPacket temp = new SfPacket(); 216 217 //get the sent data 218 Status status = sfTcpSocket_receivePacket(sfPtr, temp.sfPtr); 219 220 //put data into the packet so that it can process it first if it wants. 221 packet.onRecieve(temp.getData()); 222 223 return status; 224 } 225 } 226 227 unittest 228 { 229 //TODO: Expand to use more methods in TcpSocket 230 version(DSFML_Unittest_Network) 231 { 232 import std.stdio; 233 import dsfml.network.tcplistener; 234 235 writeln("Unittest for Tcp Socket"); 236 237 //socket connecting to server 238 auto clientSocket = new TcpSocket(); 239 240 //listener looking for new sockets 241 auto listener = new TcpListener(); 242 listener.listen(55003); 243 244 //get our client socket to connect to the server 245 clientSocket.connect(IpAddress.LocalHost, 55003); 246 247 248 249 //packet to send data 250 auto sendPacket = new Packet(); 251 252 253 //Packet to receive data 254 auto receivePacket = new Packet(); 255 256 //socket on the server side connected to the client's socket 257 auto serverSocket = new TcpSocket(); 258 259 //accepts a new connection and binds it to the socket in the parameter 260 listener.accept(serverSocket); 261 262 string temp = "I'm sending you stuff!"; 263 264 //Let's greet the server! 265 //sendPacket.writeString("Hello, I'm a client!"); 266 //clientSocket.send(sendPacket); 267 268 clientSocket.send(temp); 269 270 //And get the data on the server side 271 //serverSocket.receive(receivePacket); 272 273 char[1024] temp2; 274 size_t received; 275 276 serverSocket.receive(temp2, received); 277 278 //What did we get from the client? 279 writeln("Gotten from client: ", cast(string)temp2[0..received]); 280 281 //clear the packets to send/get new information 282 sendPacket.clear(); 283 receivePacket.clear(); 284 285 //Respond back to the client 286 sendPacket.write("Hello, I'm your server."); 287 288 serverSocket.send(sendPacket); 289 290 clientSocket.receive(receivePacket); 291 292 293 string message; 294 receivePacket.read!string(message); 295 writeln("Gotten from server: ", message); 296 297 clientSocket.disconnect(); 298 writeln(); 299 } 300 } 301 302 package extern(C): 303 304 struct sfTcpSocket; 305 306 //Create a new TCP socket 307 sfTcpSocket* sfTcpSocket_create(); 308 309 310 //Destroy a TCP socket 311 void sfTcpSocket_destroy(sfTcpSocket* socket); 312 313 314 //Set the blocking state of a TCP listener 315 void sfTcpSocket_setBlocking(sfTcpSocket* socket, bool blocking); 316 317 318 //Tell whether a TCP socket is in blocking or non-blocking mode 319 bool sfTcpSocket_isBlocking(const(sfTcpSocket)* socket); 320 321 322 //Get the port to which a TCP socket is bound locally 323 ushort sfTcpSocket_getLocalPort(const(sfTcpSocket)* socket); 324 325 326 //Get the address of the connected peer of a TCP socket 327 void sfTcpSocket_getRemoteAddress(const(sfTcpSocket)* socket, char* ipAddress); 328 329 330 //Get the port of the connected peer to which a TCP socket is connected 331 ushort sfTcpSocket_getRemotePort(const(sfTcpSocket)* socket); 332 333 334 //Connect a TCP socket to a remote peer 335 Socket.Status sfTcpSocket_connect(sfTcpSocket* socket, const(char)* hostIP, ushort port, long timeout); 336 337 338 //Disconnect a TCP socket from its remote peer 339 void sfTcpSocket_disconnect(sfTcpSocket* socket); 340 341 342 //Send raw data to the remote peer of a TCP socket 343 Socket.Status sfTcpSocket_send(sfTcpSocket* socket, const void* data, size_t size); 344 345 346 //Receive raw data from the remote peer of a TCP socket 347 void* sfTcpSocket_receive(sfTcpSocket* socket, size_t maxSize, size_t* sizeReceived, Socket.Status* status); 348 349 350 //Send a formatted packet of data to the remote peer of a TCP socket 351 Socket.Status sfTcpSocket_sendPacket(sfTcpSocket* socket, sfPacket* packet); 352 353 354 //Receive a formatted packet of data from the remote peer 355 Socket.Status sfTcpSocket_receivePacket(sfTcpSocket* socket, sfPacket* packet); 356 357 const(char)* sfErr_getOutput();