Why 10049 error occurs in udp communication even though ip and port are entered correctly - tcp

DWORD WINAPI socketRead(void *lpVoid)
{
while (true)
{
// UDP socket
WSADATA data_s;
WORD version = MAKEWORD(2, 2);
// socket start
int wsok = WSAStartup(version, &data_s);
if (wsok != 0)
{
cout << "Can't start Winsock!" << wsok;
return 0;
}
else
{
cout << "start Winsock!\n";
}
// socket bind
SOCKET in = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN serverHint = {};
memset(&serverHint, 0, sizeof(serverHint));
serverHint.sin_family = AF_INET; // IPv4
serverHint.sin_addr.S_un.S_addr = inet_addr("192.168.0.69");
serverHint.sin_port = htons(1480);
if (bind(in, (sockaddr *)&serverHint, sizeof(serverHint)) != SOCKET_ERROR)
{
cout << "bind socket!\n";
}
else
{
cout << "can't bind socket!" << WSAGetLastError() << endl;
// socket clean
int wsokE = WSACleanup();
if (wsokE != 0)
{
cout << "Can't cleanup Winsock!" << wsokE;
}
else
{
cout << "cleanup Winsock!\n";
}
// return 0;
}
}
this is my code. I want to do UDP socket communication using winsocket.
It is trying to do udp communication with another computer.
However, I keep getting error 10049 even though I wrote down the ip address and port number correctly.
The 1480 port I wrote down in the code is what I set arbitrarily. Do I need to do other processing on the computer?
When I use the same ip and port in the incoming and outgoing confirmation program called Ezterm, the values ​​come normally.
In conclusion, we want to receive data from "192.168.0.69".

Related

QSerialPort detecting lost connection

My setup is as follows: Arduino Mega UART3 <--> Voltage Level shifter <--> Rpi4
All the code can be found here
Data is being sent synchronously from the Arduino to the Rpi at 100ms and 1000ms (depending on the importance of the data). And also data is being sent from the Rpi back to the Arduino asynchronously on GUI input (There is also a sync sent at 1000ms in case some frames are lost/corrupted).
Coms are handled in a separate thread than the GUI to provide the best user experience.
Well, all is working fine but I have been trying unsuccessfully to detect if the Rpi has lost connection with the Arduino. (In the other direction is covered with a serial watchdog.)
I wanted to avoid the use of another watchdog in the Qt part but I cannot find a suitable signal to detect the lost serial connection as the QSerialPort keeps reporting a Timeout error randomly... and there are no other methods that detect successfully the disconnection.
Here below is the workaround that I am trying to use without much success: (Probably it needs a major rewrite... but I need to be pointed in the right direction first)
// Serial Port Initialization
m_Serial = new QSerialPort();
m_Serial->setPortName("ttyS0");
//m_Serial->setPortName("ttyUSB0");
m_Serial->setBaudRate(QSerialPort::Baud115200);
m_Serial->setDataBits(QSerialPort::Data8);
m_Serial->setParity(QSerialPort::NoParity);
m_Serial->setStopBits(QSerialPort::OneStop);
m_Serial->setFlowControl(QSerialPort::NoFlowControl);
m_Serial->open(QIODevice::ReadWrite);
qDebug() << "SerialPort Status: " << m_Serial->isOpen();
emit serialConnected(m_Serial->isReadable());
while(!abort)
{
QThread::msleep(5);
while (!isConected(m_Serial)){
emit serialConnected(false);
isSerialConected = false;
QThread::sleep(1);
qDebug() << "Serial Error: ";
//qDebug() << "Is readable?: " << m_Serial->isReadable();
//qDebug() << "Bytes availiable?: " << m_Serial->bytesAvailable();
mutex.lock();
abort = _abort;
mutex.unlock();
}
if (!isSerialConected){
emit serialConnected(true);
isSerialConected=true;
}
mutex.lock();
abort = _abort;
mutex.unlock();
if(!m_outFrameQueue->isEmpty())
{
//qDebug() << "Frame empty";
{ *sendData*}
} else
{
if (m_Serial->waitForReadyRead(10) )
{ *readData*}
And the function that I am trying to use to detect if is actually connected:
bool SerialWorker::isConected(QSerialPort *m_Serial){
// qDebug() << "SerialPort Error: " << m_Serial->error();
// qDebug() << "SerialPort isReadable: " << m_Serial->isReadable();
// qDebug() << "SerialPort isReadable: " << m_Serial->bytesAvailable();
if (m_Serial->error() == QSerialPort::SerialPortError::NoError){
return true;
}
else if (m_Serial->error() == QSerialPort::SerialPortError::TimeoutError){
m_Serial->clearError();
//m_Serial->reset();
return true;
}else{
m_Serial->reset();
m_Serial->close();
m_Serial->clearError();
QThread::sleep(1);
m_Serial->open(QIODevice::ReadWrite);
return false;
}
}

How to connect using UDP to my pic32 and get an answer from it

I want to connet with Qt on windows to my PIC32 UDP server. With a test program in C, I can connect and get the answer, but with Qt it is impossible. What am I doing wrong ?
As you can see I use an ACTIVE WAITING with the while, and my slot doesn't seems to be triggered. Maybe you can see my mistake here ? I hate active waiting....
Here is my code on Qt :
void MuTweezer::run()
{
QHostAddress sender;
quint16 senderPort;
QByteArray datagram;
qint64 pendingBytes;
int cpt = 0;
// Message to send
QByteArray message("Hello that's charly");
// m_imuRcvSocket.bind(10000); why is it for in a client side !?
// SEEMS to NOT BE TRIGGERED
connect(&m_imuRcvSocket, SIGNAL(readyRead()), this, SLOT(recu()));
while(m_isRunning && cpt++ < 10)
{
// send the initial message
qint64 bytesSent= m_imuRcvSocket.writeDatagram(message, QHostAddress("192.168.0.15"), 10000);
cout << "Bytes sent : " << bytesSent << endl;
// We wait the answer from the server
while(!m_imuRcvSocket.hasPendingDatagrams());
// If there is no datagram available, this function returns -1
if((pendingBytes = m_imuRcvSocket.pendingDatagramSize()) == -1)
continue;
datagram.resize(pendingBytes);
m_imuRcvSocket.readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
cout << "================="
<< "\nMessage from <" << sender.toString().toStdString().substr(7) << "> on port " << senderPort
<< "\nString : " << datagram.data()
<< "\nSize: " << pendingBytes << " Bytes (characters)\n"
<< "=================" <<
endl;
}
}
Here is my code on the PIC32, as you can see, once I receive a message, I send the answer, it allows me to make a bidirectionnal communication :
if(!UDPIsOpened(mySocket)){
DBPRINTF("Socket CLOSED");
continue; // go back to loop beginning
}
DBPRINTF("Socket OPEN");
if(!(lengthToGet = UDPIsGetReady(mySocket)))
continue;
// get the string
// UDPGetArray : returns the number of bytes successfully read from the UDP buffer.
if((lengthWeGot = UDPGetArray(message, lengthToGet)))
UDPDiscard(); // Discards any remaining RX data from a UDP socket.
/* Modifie it and send it back */
if(UDPIsPutReady(mySocket)){
message[20]= 'Z';
message[21]= 'i';
message[22]= 'b';
message[23]= 'o';
UDPPutArray(message, lengthWeGot);
UDPFlush();
}
Any idea ?
Try to use waitForBytesWritten and waitForReadyRead:
// to receive datagrams, the socket needs to be bound to an address and port
m_imuRcvSocket.bind();
// send the initial message
QByteArray message("Hi it's Charly");
qint64 bytesSent= m_imuRcvSocket.writeDatagram(message,
QHostAddress("200.0.0.3"),
10000);
bool datagramWritten = m_imuRcvSocket.waitForBytesWritten();
// add code to check datagramWritten
datagram.resize(50); // random size for testing
bool datagramReady = m_imuRcvSocket.waitForReadyRead() && m_imuRcvSocket.hasPendingDatagrams();
// add code to check datagramReady
m_imuRcvSocket.readDatagram(datagram.data(),
datagram.size(),
&sender,
&senderPort);
cout << "================="
<< "\nMessage from <" << sender << "> on port " << senderPort
<< "\nString : " << datagram
<< "\nSize: " << pendingBytes << " Bytes (characters)\n"
<< "=================" <<
endl;
A better alternative would be to use signals and slots as described in the documentation of QUdpSocket
if you plan to use the microprocessor as a client with UDP you need the MAC address of the destination machine otherwise it will not work. This one took me 4 hours to figure out.

HTTP GET problems

I'm trying to send GET request to generate receiving address (Blockchain api, https://blockchain.info/ru/api/api_receive)
On the page i've generated request - "
/api/receive?method=create&cors=true&format=plain&address=1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq&shared=false&callback=http%3A%2F%2Fgoogle.com
and need to receive an answer -
{"callback_url":"http://google.com","input_address":"16ofW1jBBLbVnDQWJsyL6NKq7hKms9tDLP","destination":"1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq","fee_percent":0}"
I found sample code and trying to send request
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.google.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
std::cout << "Connecting...\n";
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0){
std::cout << "Could not connect";
return -1;
}
std::cout << "Connected.\n";
send(Socket, "GET /api/receive?method=create&cors=true&format=plain&address=1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq&shared=false&callback=http://microsoft.com/ HTTP/1.1\r\nHost: blockchain.info\r\nConnection: close\r\n\r\n", strlen("GET /api/receive?method=create&cors=true&format=plain&address=1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq&shared=false&callback=http://microsoft.com/ HTTP/1.1\r\nHost: blockchain.info\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
return 1;
}
but receive 404 error. What is the problem and what is the best way to parse an answer (I need to get "input_address")? Thanks for help!

TCP - Identity of timed out client

I want to know the identity of the timed out client ?
how ?
if the function that will receive data like this ..How can I know the client ID ?
your help will be greatly appreciated
Thank you :)
DWORD WINAPI Server::ClientThread(LPVOID lpParam)
{
char receivedData[BUFFER_SIZE];
ThreadData myThreadData = *(ThreadData*)lpParam;
while (1)
{
int returnValue;
// Perform a blocking recv() call
returnValue = recv(myThreadData.clientSocket, receivedData, BUFFER_SIZE, 0);
if (returnValue == 0)
break;
else if (returnValue == SOCKET_ERROR)
{
cout << "recv() failed - Error Code : " << WSAGetLastError() << endl;
}
else
{
receivedData[returnValue] = '\0';
cout << "I am the server and received " << receivedData << endl;
UnderstandComingMessage(receivedData, myThreadData);
}
}
}
I don't know what you mean by 'identity', but you can get the peer IP address and port by calling getpeername() on the socket.

How to use function "send" (Winsock) to stream video in VS10 with OpenCV?

I used OpenCV on VS10 to stream video from my webcam. I also used winsock2 to transmit a message and an image in the same computer from server-client TCP/IP (local host). Now I'm trying to stream video in real-timing. I don't know if with function "send" I can specify the length of each frame because I think that it can also send a constant char. Anyone know what function could I use to solve my problem?
Source code:
Server.cpp
#include "Server.h"
using namespace std;
//Our main function
//void main()
int _tmain(int argc, _TCHAR* argv[])
{
//We have to start de Winsock-dll
long answer;
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD (2,1);
//Stard the dll
answer = WSAStartup(DLLVERSION, &wsaData);
//The dll was started, now I use the winsock funcitions in the program
//Structure for the sockets
SOCKADDR_IN addr;
//addr = our structure
int addrlen = sizeof(addr);
//Now we have to create our sockets
//sListen = socket which is listening for incoming connection
SOCKET sListen;
//sConnect = socket which is operating if a connection was found!
SOCKET sConnect;
//Now we have to setup our sockets:
//AF_INET = means that our socket belongs to the internet family
//SOCK_STREAM = means that our socket is a connection-orientated socket
sConnect = socket(AF_INET, SOCK_STREAM, NULL);
//Now we have to setup our structure
//inet_addr = IP of our socket (I use 127.0.0.1...this is the loopback adress)
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
//Retype the family
addr.sin_family = AF_INET;
//Now we have to setup the port in the structure;
//Now our server has the IP: 127.0.0.1 and the port 1234
addr.sin_port = htons (1234);
//Now we have to setup our sListen socket
sListen = socket(AF_INET, SOCK_STREAM, NULL);
//Now we blind the socket
//The socket becomes the structure addr
bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
//We have to say that the socket is listening for an incoming connection
listen(sListen, SOMAXCONN);
//SOMAXCON means that the server is listenning without any limit
//We have to start the capture of the frames to send it
//Well first of all initialize the frames and the default camera
//Using OpenCV
CvCapture *capture = 0;
IplImage *frame = 0;
int key = 0;
capture = cvCaptureFromCAM(0);
//At last we have to say what the serve sould do if a connection was found!
//For this we create a endless loop:
for(;;)
{
cout << "Waiting for an incoming connection" <<endl;
//if a connection was found << "..." <<endl
if(sConnect = accept(sListen, (SOCKADDR*)&addr, &addrlen))
{
cout << "A connection was found" <<endl;
//Second part in reference to Youtube 2
//1r: The server should send a message with the funcion send();
//The number of the letters +1
//Ex: Number of the letters: 14+1=15
answer = send(sConnect, "Bonjour",8, NULL);
//*************************Third part of the project
//Sending an image captured from the cam
//always check
if ( !capture )
{
fprintf( stderr, "Cannot open initialize webcam!\n" );
return 1;
}
//create a window for the video
cvNamedWindow( "server", CV_WINDOW_AUTOSIZE );
while( key != 'q' )
{
//get a frame
frame = cvQueryFrame(capture);
//always check
if( !frame ) break;
//display current frame
cvShowImage( "server", frame );
//exit if user press 'q'
key = cvWaitKey(1);
}
char StartStream(IplImage *frame);
int streamSize(IplImage *frame);
if(frame!=0)
{
return sizeof(*frame->imageData);
}
char* buffer = new char[10000];
int len = 10000;
//int sent = 0;
for(int i=0; i<len; i+= answer)
{
answer = send(sConnect, buffer+i, len-i, 0);
}
}
//free memory
cvDestroyWindow( "server" );
cvReleaseCapture( &capture );
}
return 0;
}
Client.cpp
#include "Client.h"
using namespace std;
//void main()
int _tmain(int argc, _TCHAR* argv[])
{
string confirm;
char message[200];
string strmessage;
//IplImage *pImg;
//Start the functions of the Winsock-DLL
long answer;
WSAData wsaData;
WORD DLLVersion;
DLLVersion = MAKEWORD(2,1);
answer = WSAStartup(DLLVersion, &wsaData);
//Setup our Sockets and SOCKADDR_IN
SOCKADDR_IN addr;
//we will need addrlen later maybe!
int addrlen = sizeof(addr);
//Now setup our Socket
SOCKET sConnect;
sConnect = socket(AF_INET, SOCK_STREAM, NULL);
//IP of our server
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
//Now we have to retype de family
addr.sin_family = AF_INET;
//Port of our server
addr.sin_port = htons(1234);
//Now we will ask the client if he wants to connect
cout << "Do you want to connect to your server? [Y/N]" <<endl;
cin >> confirm;
//If the user don't want to connect the client will close
if (confirm == "N")
{
exit(1);
}
else
{
if (confirm == "Y")
{
//function connect
connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
//Our client is working
//Now we program the client that he should recv a message from the server
//Our client should receive the message with the function recv();
//With new char "message"
answer = recv(sConnect, message, sizeof(message), NULL);
//The client should display the message
//With new string strmessage
strmessage = message;
cout << strmessage <<endl;
//the client also should display the image recived
char* buffer = new char[10000];
int len = 10000;
//int rec = 0;
int i=0;
for(int i=0; i<len; i+= answer)
{
while (answer = recv(sConnect, buffer+i, len-i, 0))
{
IplImage *frame = cvCreateImage(cvSize(640,480), 8, 3);
frame->imageData = (char *)buffer;
cvNamedWindow( "client", CV_WINDOW_AUTOSIZE );
cvShowImage( "client", frame );
}
return 0;
}
getchar();
}
}
getchar();
}
I receive the message and the confirmation of the connection in the server. And also it opens the webcam but the client doesn't receive anything.
You can try the cv_video_server and client.

Resources