How do I catch the COMException thrown by disconnected StreamSocket in C++/CX? - sockets

I'm writing an application that should retranslate some data received from Bluetooth LE device to all TCP clients connected to it. The platform is Windows 10. For now it is console application with C++/CX enable as Bluetooth LE API is only available from WinRT. The BLE part is ready but I cannot make proper TCP server using WinRT.
I'm creating TCP socket server using StreamSocketListener and store all StreamSocket objects in std::vector. In a loop iterate the vector and send the data to all connected clients. Everything is working fine at this point. But should one client disconnect and the server crashes as it tries to send a data to disconnected socket and throws COMException and I cannot catch it.
Visual Studio 2015 crash message: Exception thrown at 0x752ADAE8 in SensoCLI.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x02EFE1C0. Call stack points to auto sent = writeTask.get();
Below is the minimal listing of my app that corresponds to the problem:
#include "pch.h"
#using <platform.winmd>
#using <Windows.winmd>
using namespace std;
using namespace Windows::Foundation;
using namespace Platform;
using namespace concurrency;
namespace WFC = Windows::Foundation::Collections;
namespace WNS = Windows::Networking::Sockets;
namespace WSS = Windows::Storage::Streams;
bool shouldStop = false;
// TCP socket server
WNS::StreamSocketListener ^tcpListener;
vector<WNS::StreamSocket ^> *tcpClients;
void OnSocketConnectionReceived(WNS::StreamSocketListener ^aListener, WNS::StreamSocketListenerConnectionReceivedEventArgs ^args);
int main(Array<String ^> ^args)
{
tcpClients = new vector<WNS::StreamSocket ^>();
tcpListener = ref new WNS::StreamSocketListener();
tcpListener->ConnectionReceived += ref new TypedEventHandler<WNS::StreamSocketListener ^, WNS::StreamSocketListenerConnectionReceivedEventArgs ^>(&OnSocketConnectionReceived);
auto listenTask = create_task(tcpListener->BindServiceNameAsync("53450"));
listenTask.wait();
while (!shouldStop)
{
if (tcpClients->size() > 0)
{
auto netDataStream = ref new WSS::InMemoryRandomAccessStream();
auto writer = ref new WSS::DataWriter(netDataStream);
auto reader = ref new WSS::DataReader(netDataStream->GetInputStreamAt(0));
String^ stringToSend("Hello");
writer->WriteUInt32(writer->MeasureString(stringToSend));
writer->WriteString(stringToSend);
auto aTask = create_task(writer->StoreAsync());
unsigned int bytesStored = aTask.get();
aTask = create_task(reader->LoadAsync(bytesStored));
aTask.wait();
auto netData = reader->ReadBuffer(bytesStored);
for (auto iter = tcpClients->begin(); iter != tcpClients->end(); ++iter)
{
create_task((*iter)->OutputStream->WriteAsync(netData)).then([](task<unsigned int> writeTask) {
try
{
// Try getting an exception.
auto sent = writeTask.get();
wcout << L"Sent: " << sent << endl;
}
catch (Exception^ exception)
{
wcout << L"Send failed with error: " << exception->Message->Data() << " " << endl;
}
});
}
Sleep(1000);
}
}
}
void OnSocketConnectionReceived(WNS::StreamSocketListener ^aListener, WNS::StreamSocketListenerConnectionReceivedEventArgs ^args)
{
auto sock = args->Socket;
tcpClients->push_back(sock);
}
How do I properly catch the exception and handle disconnected StreamSocket?

Related

Unable to send publish messages from esp8266 to Raspberry (Broker) using MQTT. Getting Socket Error <Random Device Id>, Disconnecting

I am trying to send and receive a messages from Raspberry Pi (Broker) to Arduino-ESP8266 (client) using MQTT. What I am trying to achieve is pretty basic for now. The broker sends a start command and the client on receving the message should send back a random number. I am able to read the message sent by the broker but the messages from the client are never sent. Here is the code that I am using
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(19, 18); //RX, TX
#endif
#define MQTT_KEEPALIVE 10
#include <PubSubClient.h>
IPAddress server(192, 168, 0, 105);
char ssid[] = "user1956";
char password[] = "******";
int status = WL_IDLE_STATUS; //wifi radio's status
//MQTT
//const char* mqtt_topic = "Rpi_Master";
const char* mqtt_username = "pi";
const char* mqtt_password = "********";
//client Id
const char* clientID = "A_2";
//Variables for numbers
long randNumber1;
String rn1;
char rn1_char[50];
WiFiEspClient wifiClient;
PubSubClient client(wifiClient); //1883 is the listener port for the broker
void setup() {
// Initilize serial for debugging
Serial.begin(115200);
//initilize serial for ESP module
Serial1.begin(115200);
//initilize the ESP module
WiFi.init(&Serial1);
if (WiFi.status() == WL_NO_SHIELD)
{
Serial.println("WiFi shield not present");
while (true);
}
while (status != WL_CONNECTED)
{
Serial.print("Attempting to connect to WPA SSID : ");
Serial.println(ssid);
status = WiFi.begin(ssid, password);
}
Serial.println("You are connected to the network");
client.setServer(server, 1883);
client.setCallback(callback);
//Allow the hardware to sort itself
delay(1500);
randomSeed(50);
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message Received: [");
Serial.print(topic);
Serial.println("]");
Serial.print("Message is:");
String message = (char *)payload;
Serial.println(message);
else if (!strncmp((char *)payload, "B1", length)) //Start code can be changed to any string value in place of 1
{
client.publish("Ad_B", "OK");
generateRandomData();
}
else if (!strncmp((char *)payload, "B2", length)) //Start code can be changed to any string value in place of 1
{
client.publish("Ad_B", "OK");
generateRandomData();
}
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
delay(1000);
}
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT Connection...");
//Attempt to Connect
if (client.connect(clientID, mqtt_username, mqtt_password))
{
Serial.println("connected");
//Once connected publish an announcement
client.publish("Ad_B", "Ready");
//and resubscribe
client.subscribe("Rpi_Master"); //This name can be changed
}
else
{
Serial.print("failed, rc = ");
Serial.print(client.state());
Serial.println("Trying again in 5 seconds");
//Wait for 5 seconds before retrying
delay(5000);
}
}
}
void generateRandomData(){
randNumber1 = random(0,0); //(14000,15000)
//Serial.println(randNumber1); // print a random number from 0to 299
rn1 = String(randNumber1);
rn1.toCharArray(rn1_char, rn1.length() + 1);
client.publish("LC_B_1", rn1_char);
client.publish("Ad_B", "End");
}
This is the output of the serial monitor that I am receiving:
07:45:42.016 -> [WiFiEsp] Initializing ESP module
07:45:45.430 -> [WiFiEsp] Initilization successful - 1.5.4
07:45:45.430 -> Attempting to connect to WPA SSID : No Free Wifi
07:45:50.464 -> [WiFiEsp] Connected to No Free Wifi
07:45:50.464 -> You are connected to the network
07:45:51.940 -> Attempting MQTT Connection...[WiFiEsp] Connecting to 192.168.0.105
07:45:52.084 -> connected
07:46:31.926 -> Message Received: [Rpi_Master]
07:46:31.926 -> Message is:B2ter
07:46:37.438 -> [WiFiEsp] TIMEOUT: 20
08:20:58.967 -> [WiFiEsp] >>> TIMEOUT >>>
The client is unable to publish any messages. The mosquitto log shows PINGREQ and RINGRESP to a random id and client.publish stops with the following message in the log - Socket Error on Client <Some Random Client Id>, Disconnecting. Attached the screenshot of the log. Is there any way to know what the unknown client is? Please help me to sort this issue. Thanks.
You generateRandom() function blocks (15 seconds) for longer than the keep alive (10 seconds) timeout and this will block the client.loop() function so it will not be able to send keep alive packets.

boost async_accept not working with the boost asio use_future option

I want to listen on a boost::asio::ip::tcp::socket with a timeout. For this, I am using the std::future::wait_for function. Below is my code:
std::optional<boost::asio::ip::tcp::socket> server::listen()
{
boost::asio::ip::tcp::socket sock(io_service);
std::future<void> accept_status = acceptor.async_accept(
sock, boost::asio::use_future);
if (accept_status.wait_for(std::chrono::seconds(10)) == std::future_status::timeout)
{
// I hope there's no race-condition between
// accepting a connection and calling cancel
acceptor.cancel();
std::cerr << "Timeout" << std::endl;
return {};
}
std::cerr << "Accepted a connection" << std::endl;
return {std::move(sock)};
}
This is not working though: the client is able to connect, but I still get a timeout. Which means that the future object and the asynchronous accept function aren't communicating. What am I missing?
I am using Boost version 1.65.
For Explorer_N, following is a complete program that does not work the way I expect:
#include <boost/asio.hpp>
#include <boost/asio/use_future.hpp>
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
using namespace std;
void server_listen() {
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 31132);
boost::asio::ip::tcp::acceptor acceptor(io_service, endpoint);
boost::asio::ip::tcp::socket socket(io_service);
std::future<void> accept_status = acceptor.async_accept(
socket, boost::asio::use_future);
while(true) {
if(accept_status.wait_for(std::chrono::seconds(10)) == std::future_status::timeout) {
acceptor.cancel();
std::cerr << "Timeout\n";
} else {
break;
}
}
// if I replace the lines starting from the async_accept call
// by just the following, everything works as expected
// acceptor.accept(socket);
std::cout << "Accepted a connection\n";
while(true) {
}
}
void client_connect() {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(*resolver.resolve({"127.0.0.1", std::to_string(31132)}));
socket.connect(endpoint);
std::cout << "Connected to server\n";
while(true) {
}
}
int main() {
std::thread server(server_listen);
std::this_thread::sleep_for(std::chrono::seconds(2));
std::thread client(client_connect);
while(true) {
}
}
Compiled by g++ -std=c++17 <program>.cpp -lpthread -lboost_system -o <program>.
The output I get is:
Connected to server
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
Timeout
...
To answer your claims:
"future object and the asynchronous accept function aren't communicating" -- not possible.
"the client is able to connect, but I still get a timeout.", -- your client connecting to a listener is one event and executing completion-handler (setting promise) is an another event.
So connection could've accepted at 9th second and callback would have scheduled to run at 11th second (for instance).
Remember, we are dealing with asynchronous ops, so making absolute prediction on future events is not something right I would say.
apart form that
// I hope there's no race-condition between
// accepting a connection and calling cancel
acceptor.cancel();
std::cerr << "Timeout" << std::endl;
return {};
acceptor.cancel(); just collect the pending waiters, and complete them with ec set to operation_aborted, if the handlers are already out to completion event queue, then cancel() is a no-op
Extending my answer based on OP's recent edit:
using namespace std;
void server_listen() {
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 31132);
boost::asio::ip::tcp::acceptor acceptor(io_service, endpoint);
boost::asio::ip::tcp::socket socket(io_service);
auto work = make_work_guard(io_service);
using type= std::decay_t<decltype(work)>;
std::thread io([&](){io_service.run();});
std::future<void> accept_status = acceptor.async_accept(
socket, boost::asio::use_future);
if(accept_status.wait_for(std::chrono::seconds(10)) == std::future_status::timeout) {
acceptor.cancel();
std::cerr << "Timeout\n";
work.~type();
//break;
} else {
std::cout<<"future is ready\n";
work.~type();
// break;
}
io.join();
// if I replace the lines starting from the async_accept call
// by just the following, everything works as expected
// acceptor.accept(socket);
std::cout << "Accepted a connection\n";
}
void client_connect() {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::ip::tcp::endpoint endpoint(*resolver.resolve({"127.0.0.1", std::to_string(31132)}));
socket.connect(endpoint);
std::cout << "Connected to server\n";
}
enter code here
int main() {
std::thread server(server_listen);
std::this_thread::sleep_for(std::chrono::seconds(2));
std::thread client(client_connect);
server.join(); client.join();
}
There are many things to take care of in your program (avoid unnecessary spin-loop, don't forgot to either join or detach the std::thread and make sure you call io_service::run when you use async* version)
Start
Connected to server
future is ready
Accepted a connection
0
Finish

how to catch the socket programming's send and receive request in fiddler

i have the code for creating a socket in c++.the code is running fine.the code is:
#include <winsock2.h>
#include <WS2tcpip.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib") using namespace std;
int main (){
// Initialize Dependencies to the Windows Socket.
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
return -1;
}
// We first prepare some "hints" for the "getaddrinfo" function
// to tell it, that we are looking for a IPv4 TCP Connection.
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; // We are targeting IPv4
hints.ai_protocol = IPPROTO_TCP; // We are targeting TCP
hints.ai_socktype = SOCK_STREAM; // We are targeting TCP so its SOCK_STREAM
// Aquiring of the IPv4 address of a host using the newer
// "getaddrinfo" function which outdated "gethostbyname".
// It will search for IPv4 addresses using the TCP-Protocol.
struct addrinfo* targetAdressInfo = NULL;
DWORD getAddrRes = getaddrinfo("www.google.com", NULL, &hints, &targetAdressInfo);
if (getAddrRes != 0 || targetAdressInfo == NULL)
{
cout << "Could not resolve the Host Name" << endl;
system("pause");
WSACleanup();
return -1;
}
// Create the Socket Address Informations, using IPv4
// We dont have to take care of sin_zero, it is only used to extend the length of SOCKADDR_IN to the size of SOCKADDR
SOCKADDR_IN sockAddr;
sockAddr.sin_addr = ((struct sockaddr_in*) targetAdressInfo->ai_addr)->sin_addr; // The IPv4 Address from the Address Resolution Result
sockAddr.sin_family = AF_INET; // IPv4
sockAddr.sin_port = htons(80); // HTTP Port: 80
// We have to free the Address-Information from getaddrinfo again
freeaddrinfo(targetAdressInfo);
// Creation of a socket for the communication with the Web Server,
// using IPv4 and the TCP-Protocol
SOCKET webSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (webSocket == INVALID_SOCKET)
{
cout << "Creation of the Socket Failed" << endl;
system("pause");
WSACleanup();
return -1;
}
// Establishing a connection to the web Socket
cout << "Connecting...\n";
if(connect(webSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) != 0)
{
cout << "Could not connect";
system("pause");
closesocket(webSocket);
WSACleanup();
return -1;
}
cout << "Connected.\n";
// Sending a HTTP-GET-Request to the Web Server
const char* httpRequest = "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n";
int sentBytes = send(webSocket, httpRequest, strlen(httpRequest),0);
if (sentBytes < strlen(httpRequest) || sentBytes == SOCKET_ERROR)
{
cout << "Could not send the request to the Server" << endl;
system("pause");
closesocket(webSocket);
WSACleanup();
return -1;
}
// Receiving and Displaying an answer from the Web Server
char buffer[10000];
ZeroMemory(buffer, sizeof(buffer));
int dataLen;
while ((dataLen = recv(webSocket, buffer, sizeof(buffer), 0) > 0))
{
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
// Cleaning up Windows Socket Dependencies
closesocket(webSocket);
WSACleanup();
system("pause");
return 0; }
I want to capture the request and response in fiddler while sending and receiving the request but fiddler is not catching it.
thanks in advance
Fiddler inserts itself into the stack as an HTTP proxy server. It relies on the web browsers to recognize that there is a proxy configured on the PC and to send through that. Your code does not detect for a proxy to send through - so Fiddler won't be able to monitor your traffic.
You have several options.
Since you are own Windows, just switch from using direct sockets to using the WinInet HTTP API. It will do automatic proxy detection for you without you having to think about it. It will do the proxy authentication as well if its required.
OR. Use Wireshark or NetMon to analyze your traffic instead of Fiddler.
I'd recommend #1 since that means your code will work in the presence of a real proxy server (commonly found on enterprise networks) and Fiddler will just work with it.
I suppose there is a third option where you auto-detect the browser proxy settings, then create a socket to the proxy, speak the HTTP PROXY protocol, etc... but that's not the best practice.

RMI and 2 machines - two way communication

I've got problem with RMI comunication between 2 machines (win 7 and win xp VM). The exception with I have problem is:
java.rmi.ConnectException: Connection refused to host: 169.254.161.21; nested exception is:
java.net.ConnectException: Connection timed out: connect
It's really weired because during connection I use address 192.168.1.4 (server), but exception somehow show sth different. I disabled firewall on both side. Ping working to both side. I tried telnet to server and use server port:
telnet 192.168.1.4 1099 and it's working... I can't figure out where the problem is.
If I run this on host side (eg server side) everything works fine.
How is it look from SERVER:
public class Server
{
public static void main(String args[])
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
String portNum, registryURL;
try{
System.out.println("Enter the RMIregistry port number:");
portNum = (br.readLine()).trim();
int RMIPortNum = Integer.parseInt(portNum);
startRegistry(RMIPortNum); // Registry registry = LocateRegistry.createRegistry(RMIPortNum);
ServerSide_Impl exportedObj = new ServerSide_Impl();
registryURL = "rmi://localhost:" + portNum + "/callback";
//registryURL = "rmi://192.168.1.4:" + portNum + "/callback";
Naming.rebind(registryURL, exportedObj);
System.out.println("Callback Server ready.");
}// end try
catch (Exception re) {
System.out.println(
"Exception in HelloServer.main: " + re);
} // end catch
} // end main
//This method starts a RMI registry on the local host, if
//it does not already exists at the specified port number.
private static void startRegistry(int RMIPortNum) throws RemoteException
{
try
{
Registry registry = LocateRegistry.getRegistry(RMIPortNum);
registry.list( );
// This call will throw an exception
// if the registry does not already exist
}
catch (RemoteException e)
{
Registry registry = LocateRegistry.createRegistry(RMIPortNum);
}
} // end startRegistry
} // end class
Client side is look like:
try
{
this.serverAd = serverAddress.getText();
String path = System.getProperty("user.dir");
String pathAfter = path.replace("\\", "/");
String pathFile = "file:/"+pathAfter + "/wideopen.policy";
System.setProperty("java.security.policy", pathFile);
System.setSecurityManager(new RMISecurityManager());
this.hostName = hostNameTextField.getText();
this.portNum = hostPortNumberTextField.getText();
RMIPort = Integer.parseInt(this.portNum);
this.time = Integer.parseInt(timeTextField.getText());
//this.registryURL = "rmi://localhost:" + this.portNum + "/callback";
String registryURLString = "rmi://"+this.serverAd+":" + this.portNum + "/callback";
this.registryURL = registryURLString;
ConsoleTextField.append("\n"+ this.registryURL + "\n");
// find the remote object and cast it to an
// interface object
obj = (ServerSide_Interface)Naming.lookup(this.registryURL);
boolean test = obj.Connect();
if(test)
{
callbackObj = new ClientSide_Impl();
// register for callback
obj.registerForCallback(callbackObj);
isConnected = true;
ConsoleTextField.append("Nawiązano połaczenie z serwerem\n");
TableModel modelTemp = obj.Server_GenerateStartValues();
myDataTable.setModel(modelTemp);
myDataTable.setEnabled(true);
}
else ConsoleTextField.append("Brak połączenia z serwerem\n");
}
catch (Exception ex ){
ConsoleTextField.append(ex + "\n");
System.out.println(ex);
}
This connection is working fine if I run client on host side. If I use VM and try connect between 2 different machines, I can;t figure out what did I do bad
There is something wrong with your etc/hosts file or your DNS setup. It is providing the wrong IP address to the server as the server's external IP address, so RMI embeds the wrong address into the stub, so the client attempts to connect to the wrong IP address.
If you can't fix that, you can set the system property java.rmi.server.hostname to the correct IP address at the server JVM, before exporting any RMI objects (including Registries). That tells RMI to embed that address in the stub.

SIGPIPE (Broken pipe) on tcp_disconnect to exec a client (WCF Soap 1.1 and server)

I am developing a Qt client (C++) with gSOAP lib, which is supposed to discuss with a Web Service by Microsoft (WCF). I use SOAP 1.1 on both sides.
My client code is as follows :
CustomBinding_USCOREISynchronisation service;
soap_ssl_init(); /* init OpenSSL (just once) */
soap_init2(service.soap, SOAP_IO_KEEPALIVE, SOAP_IO_KEEPALIVE);
service.soap->max_keep_alive = 1000; // at most 100 calls per keep-alive session
service.soap->accept_timeout = 6000; // optional: let server time out after ten minutes of inactivity
if (soap_ssl_client_context(service.soap,
SOAP_SSL_NO_AUTHENTICATION,
NULL, /* keyfile: required only when client must authenticate to server (see SSL docs on how to obtain this file) */
NULL, /* password to read the key file (not used with GNUTLS) */
NULL, /* cacert file to store trusted certificates (needed to verify server) */ NULL, /* capath to directory with trusted certificates */
NULL /* if randfile!=NULL: use a file with random data to seed randomness */
))
{
soap_print_fault(service.soap, stderr);
exit(1);
}
_ns1__Connect req;
_ns1__ConnectResponse resp;
std::string strLogin = "tata#gmail.com";
std::string strPassword = "681982981298192891287B0A";
bool bInternalUser = true;
req.login = &strLogin;
req.password = &strPassword;
req.isInternalUser = &bInternalUser;
int err = service.__ns1__Connect(&req, &resp);
if (SOAP_OK == err)
qDebug() << ":D";
else
{
qDebug() << "Error : " << err;
soap_print_fault(service.soap, stderr);
}
qDebug() << "Result of Connect : " << resp.ConnectResult;
Problem: when I execute the program, I get a SIGPIPE (Broken pipe) in the "tcp_disconnect" function, on the exactly line "r = SSL_shutdown (soap-> ssl);".
Error message generated:
Error -1 fault: SOAP-ENV: Client [no subcode]
"End of file or no input: Operation interrupted or timed out"
Detail: [no detail]
Do you have any idea why? If you need more resources or information, please let me know!
A big thank in advance,
Louep.