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

Function snippetForSocketReceiveFrom

Tests/Libraries/Async/AsyncTest.cpp:555–601  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

553}
554
555SC::Result snippetForSocketReceiveFrom(AsyncEventLoop& eventLoop, Console& console)
556{
557SocketDescriptor client;
558//! [AsyncSocketReceiveFromSnippet]
559// Assuming an already created (and running) AsyncEventLoop named `eventLoop`
560// ...
561char receivedData[100] = {0}; // A buffer to hold data read from the socket
562AsyncSocketReceiveFrom receiveAsync;
563receiveAsync.callback = [&](AsyncSocketReceive::Result& res)
564{
565 Span<char> readData;
566 if(res.get(readData))
567 {
568 if(res.completionData.disconnected)
569 {
570 // Last callback invocation done when other side of the socket has disconnected.
571 // - completionData.disconnected is == true
572 // - readData.sizeInBytes() is == 0
573 console.print("Client disconnected");
574 }
575 else
576 {
577 // readData is a slice of receivedData with the received bytes
578 console.print("{} bytes have been read", readData.sizeInBytes());
579
580 // Get the source address / port of the received data
581 SocketIPAddress sourceAddress = res.getSourceAddress();
582 SocketIPAddress::AsciiBuffer buffer;
583 StringView formattedAddress;
584 (void)sourceAddress.toString(buffer, formattedAddress);
585 console.print("Source address: {}:{}", formattedAddress, sourceAddress.getPort());
586
587 // IMPORTANT: Reactivate the request to receive more data
588 res.reactivateRequest(true);
589 }
590 }
591 else
592 {
593 // Some error occurred, check res.returnCode
594 }
595};
596// Assuming client is an unconnected UDP Socket
597SC_TRY(receiveAsync.start(eventLoop, client, {receivedData, sizeof(receivedData)}));
598//! [AsyncSocketReceiveFromSnippet]
599SC_TRY(eventLoop.run());
600return Result(true);
601}
602
603SC::Result snippetForFileRead(AsyncEventLoop& eventLoop, Console& console)
604{

Callers

nothing calls this directly

Calls 9

printMethod · 0.80
getSourceAddressMethod · 0.80
reactivateRequestMethod · 0.80
ResultClass · 0.50
getMethod · 0.45
sizeInBytesMethod · 0.45
toStringMethod · 0.45
startMethod · 0.45
runMethod · 0.45

Tested by

no test coverage detected