MCPcopy Create free account
hub / github.com/Pagghiu/SaneCppLibraries / socketClientConnectSnippet

Method socketClientConnectSnippet

Tests/Libraries/Socket/SocketTest.cpp:338–381  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

336}
337
338SC::Result SC::SocketTest::socketClientConnectSnippet()
339{
340 SocketDescriptor serverSocket;
341 SocketServer server(serverSocket);
342
343 // Look for an available port
344 constexpr int tcpPort = 5050;
345 const StringView serverAddress = "::1"; // or "127.0.0.1"
346 SocketIPAddress nativeAddress;
347 SC_TRY(nativeAddress.fromAddressPort(serverAddress, tcpPort));
348
349 // Create a (TCP) socket and start listening
350 SocketFlags::AddressFamily family = nativeAddress.getAddressFamily();
351 SC_TRY(serverSocket.create(family));
352 SC_TRY(server.bind(nativeAddress));
353 SC_TRY(server.listen(1)); // Start listening (skip this for UDP sockets)
354
355 //! [socketClientConnectSnippet]
356
357 // ...assuming there is a socket listening at given serverAddress and tcpPort
358 SocketDescriptor clientSocket;
359 SocketClient client(clientSocket);
360
361 // Create a (TCP) socket
362 SC_TRY(clientSocket.create(family));
363
364 // [Alternatively] Create an UDP socket instead
365 // SC_TRY(clientSocket.create(family, SocketFlags::SocketDgram, SocketFlags::ProtocolUdp));
366
367 // Connect to the server
368 SC_TRY(client.connect(serverAddress, tcpPort));
369
370 // Write some data to the socket
371 const int testValue = 1;
372 char buf[1] = {testValue};
373 SC_TRY(client.write({buf, sizeof(buf)}));
374 buf[0]++; // change the value and write again
375 SC_TRY(client.write({buf, sizeof(buf)}));
376
377 // Close the socket
378 SC_TRY(clientSocket.close());
379 //! [socketClientConnectSnippet]
380 return Result(true);
381}
382
383namespace SC
384{

Callers

nothing calls this directly

Calls 7

getAddressFamilyMethod · 0.80
ResultClass · 0.50
createMethod · 0.45
bindMethod · 0.45
connectMethod · 0.45
writeMethod · 0.45
closeMethod · 0.45

Tested by

no test coverage detected