SOCKET connection: the program does not recognize the connect method - c++

I'm working on a project in Qt Creator 6.3 and I'm programming it in C++. The program uses a GUI, threads and works like a client.
I need to make a TCP/IP connection using a socket to connect to the server. I have seen several tutorials and in all of them they use the connect function to connect to the server. In all tutorials, this function is used in the main.cpp.
The problem is that I need to make this conection in the GUI and not in the main.cpp. But, when I try to use the connect method the program confuses this method with the connect method that uses slots and signals as an argument. Is there a way to tell the program which connect I want to use?
I need to make the connection in the GUI because I have threads that need to receive data from the socket and save it in variables that are from the GUI.
I need something like this:
int main(int argc, char *argv[]){
QApplication a(argc, argv);
RadarGUI w; //this is the GUI
w.show();
return a.exec();
}
In radargui.cpp a function that makes the connections with the socket
void RadarGUI::conectar_servidor(){
std::string ip= "127.0.0.1";
int port=2020;
//winsock
WSAData data;
WORD version= MAKEWORD(2,2);
int wsResultado= WSAStartup(version, &data);
if (wsResultado != 0){
printf("fallo inicializacion de winsock del cliente");
}
//socket
SOCKET sock = socket(AF_INET,SOCK_STREAM,0);
if (sock== INVALID_SOCKET){
printf("fallo creacion del socket del cliente");
WSACleanup();
}
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ip.c_str(), &hint.sin_addr);
//connect to server, HERE IS THE PROBLEM
int conectarResultado = connect(sock, (sockaddr*)&hint, sizeof(hint)); //the program think
//that this function needs signal and slot
if (conectarResultado != SOCKET_ERROR){
printf("el cliente no pudo conectarse al servidor");
closesocket(sock);
WSACleanup();
}
}
The error related to the connect method:
No matching member function for call to 'connect'
candidate function not viable: no known conversion from 'SOCKET' (aka 'unsigned long long') to 'const QObject *' for 1st argument

Related

QUDPSocket can't receive from remote Ethernet

Currently I am writing an application for Windows 10 to read UDP packets with a QUDPSocket through the Ethernet adapted to thunderbolt.
WireShark and Microsoft UDP Receiver/Sender both see the proper UDP packets and where each sender ip address, port#, local ip address and local port# are.
But whenever I try to use QUDPSocket, it has trouble receiving any packets. The readyRead() is never signaled.
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
socket = new QUdpSocket(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()), Qt::QueuedConnection);
socket->bind(QHostAddress::AnyIPv4, 56666);
}
void MainWindow::processPendingDatagrams()
{
QByteArray array;
QHostAddress sender;
quint16 senderPort;
while (socket->hasPendingDatagrams())
{
array.fill(0, socket->pendingDatagramSize());
socket->readDatagram(array.data(),
array.size(),
&sender,
&senderPort);
qDebug()<<socket->pendingDatagramSize();
}
}
I tried multiple versions of binding but none worked.
Thanks for any help in advance.

TCP Server doesn't receive data correctly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The below code has a TCP client in C and TCP Server in Qt C++. My problem is that I am using TCP for reliability, but it has data losses (not packet). In my main code, if I run tcp client to send data, TCP server receives only one packet. if I add sleep(1); to the client between each packet transfer, then TCP server receives data. Both client and server runs on the same computer.
To simplify the question and can't put too huge code here, I have the below code that performs faster, but it losses last 10-15 bytes of the packet.
TCP C client
main.c
#include "socket_handler.h" //I didn't put the all includes here
#define PORT 22208
//tcp server
int main(void)
{
int sockfd;
uint32_t senderAddress = 2130706433; //127.0.0.1
if( connect_to_server_w_uint( &sockfd, senderAddress, PORT ) < 0 ){
printf("error at line 454\n");
exit(1);
}
char data[] = "124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22 03:01:00$0000-00-00 00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$2$0£";
char buffer[512];
int i=0;
for(i=0; i<1000; i++){
bzero(buffer, 512);
sprintf(buffer, "%d***%s -----",i,data);
send_data_to_server(&sockfd, buffer, strlen(data) +1 );
printf("[%d]: data is sent\n", i);
}
close_connection(&sockfd);
return 0;
}
socket_handler.c
int connect_to_server(int *sockfd , struct in_addr senderAddress, uint16_t destPort){
struct sockaddr_in serv_addr;
*sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (*sockfd < 0)
//error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr = senderAddress;
serv_addr.sin_port = htons(destPort);
if (connect( *sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){
printf("connection error line 1413\n");
close( *sockfd );
return -1;
}
return 0;
}
int connect_to_server_w_uint(int *sockfd, uint32_t senderAddress, uint16_t destPort){
struct sockaddr_in serv_addr;
*sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (*sockfd < 0){
printf("ERROR opening socket");
close(*sockfd);
return -1;
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(senderAddress);
serv_addr.sin_port = htons(destPort);
if (connect(*sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
printf("ERROR connecting");
close(*sockfd);
return -1;
}
return 0;
}
int send_data_to_server(int *sockfd, char *message, uint16_t msgLength){
int n = write(*sockfd, message, msgLength);
if (n < 0){
printf("ERROR writing to socket");
return -1;
}
return 0;
}
int close_connection(int *sockfd){
close( *sockfd );
return 0;
}
Qt C++ TCP Server
MainWindow.cpp
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void ParseThePacket(QByteArray data);
private:
Ui::MainWindow *ui;
Server *server;
};
Client.h
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject *parent = 0);
public slots:
bool connectToHost(QString host);
bool writeData(QByteArray data);
private:
QTcpSocket *socket;
};
Server.cpp
Server::Server(QObject *parent) : QObject(parent)
{
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if( server->listen(QHostAddress::Any, PORT) ){
qDebug() << "tcp server started!";
}else{
qDebug() << "tcp server couldn't start listening";
}
}
void Server::newConnection()
{
qDebug() << "new connection";
while (server->hasPendingConnections())
{
socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
}
}
void Server::disconnected()
{
qDebug() << "disconnected";
socket->deleteLater();
}
void Server::readyRead()
{
qDebug() << "readyRead";
QByteArray buffer = socket->readAll();
emit dataReceived(buffer);
}
Here is an example output from the TCP server(the end of qDebug() output):
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$996***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$997***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$998***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$999***124b00068c158f$321$52712304$13.212779$0$O$0$0$b4$1$0$3$0$0$0$0$11$0$7$0$1$fe$f1$aaa9fffffffffd80$2132b00$eb460b5e$1$1$2016-02-22
03:01:00$0000-00-00
00:00:00$321$24754$321$13132$1$98$0$5.1$0$3c$64$1$96$4d$3e8$38$2$46$dc$4$3$f6$e6$17$0$e6$d3$1$0$e6$d3$"
disconnected
Question 1
Comparing to the original message, it misses "1$0$e6$d3$2$0£" part of the (14 byte) sent data. What is the reason of the missing message? How to fix the code that the TCP server receives the complete data.
Question 2
As I mentioned in the beginning that I am using the same code as a part of a large code and TCP server receives packets when I put sleep(1) between each packet transmission (otherwise it receives only the first packet). What is the reason of it and how to solve it?
I observed the packet transmission on Wireshark that all the TCP packets are sent successfully, but it seems like the receive part has an issue.
I am using Ubuntu 15.04, kernel 3.19.0-69-generic, gcc version 4.9.2
int n = write(*sockfd, message, msgLength);
if (n < 0){
You are only checking that write() did not return a negative value, indicating an error.
However, a write() to a socket does not guarantee that all requested bytes will be written. write() on a socket may return a positive value, fewer than msgLength here, indicating that fewer than the requested bytes have been written. This is documented, in detail, in write()'s manual page.
You are ignoring this possibility, and that's the likely reason you're missing your data. It's up to you to figure out what to do, in this case. The usual approach is to simply go back and attempt to write the remaining bytes (which, again, may not be written in their entirety).
Similarly, when reading from a socket, you are not guaranteed that everything that was written to the socket, by the sender, will be read in one gulp. It is up to you to verify that your reader has read everything that there is to read, and if the reader expects more data, continue reading from the socket until it is received.
readAll just reads all data available to the current moment.

Qt GUI for UDP packet reception

I am developing a GUI using Qt for a test UDP server application i wrote in C using the sockets interface available in unix. I aim of the GUI is to display all the messages (perror and fprintf) in either a "text edit box" or "text browser box". Here is my code,
//-----------------------------Main.Cpp------------------------------------------//
//-----------------------------QT specific headers-------------------------------//
#include "mainwindow.h"
#include <QApplication>
#include <QLabel>
//------------------------------------------------------------------------------------//
int main(int argc, char *argv[])
{
int sock_fd=0;
funct_class funct_class_obj;
QApplication a(argc, argv);
MainWindow w;
sock_fd=funct_class_obj.udp_config();
funct_class_obj.recv_fucnt(sock_fd);
return a.exec();
}
//--------------------------------End of main.cpp------------------------------//
//-----------------------------mainwindow.cpp----------------------------------//
//-----------------------------QT specific headers-----------------------------//
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QLabel>
//-----------------------------------------------------------------------------//
//--------------------------------C program specific headers------------------//
#include <stdio.h>
#include <stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
//---------------------------------------------------------------------------//
unsigned char message[50];
QString mystr;
int funct_class:: udp_config()
{
int sock_fd=0;
if ((sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
perror("\nError creating socket\n");
//mystr = "\nError creating socket\n";
else
{
fprintf(stdout, "\nSuccessfully created socket with descriptor:%d\n", sock_fd);
//mystr = "Successfully created socket";
struct sockaddr_in sock_addr = {0};
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(PORT);
if (inet_aton("127.0.0.1", &sock_addr.sin_addr) < 0)
perror("\nError converting destination IP address from dotted decimal to binary\n");
// mystr = "Error converting destination IP address from dotted decimal to binary";
else
{
if (bind(sock_fd, (struct sockaddr*)&sock_addr, sizeof(sock_addr)) < 0) // Bind function call binds the properties assigned above to the socket created earlier
perror("\nError binding the port and IP address with the socket\n");
//mystr = "Error binding the port and IP address with the socket";
else
fprintf(stdout, "\nBinding port and IP address successful\n");
// mystr = "Binding port and IP address successful";
}
}
return sock_fd;
}
void funct_class:: recv_fucnt(int sock_fd)
{
struct sockaddr_in recv_sockaddr = {0};
socklen_t recv_sockaddr_len = sizeof(recv_sockaddr);
int recv_data=0;
if ((recv_data = recvfrom(sock_fd, message, sizeof(message), 0x00, (struct sockaddr*)&recv_sockaddr, &recv_sockaddr_len)) <= 0)
perror("\nError receiving data/no data received\n");
//mystr = "Error receiving data/no data received";
else
fprintf(stdout, "\nSuccessfully received %d bytes of data\n", recv_data);
fprintf(stdout, "\nData is :%s", message);
//mystr = "Successfully received data";
mystr = QString::fromStdString((const char*)message);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->testedit->setText(mystr);
//ui->mytextbrowser->setText((mystr));
}
MainWindow::~MainWindow()
{
delete ui;
}
//-----------------------------End of mainwindow.cpp---------------------------//
//------------------------------------mainwindow.h-----------------------------//
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#define PORT 5030
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
class funct_class{
public:
int udp_config();
void recv_fucnt(int sock_fd);
};
#endif // MAINWINDOW_H
//-------------------------------End of mainwindow.h-----------------------------//
The application is compiling fine, but i am facing problems when i execute it. It just freezes and even if i manage to get it out from freeze, i am not able to display the required string either in the "text edit box" or "text browser box". Please help.
P.S.: I am a newbie to GUI programming and Cpp.
The issue seems to be pretty clear:
ui->testedit->setText(mystr);
This is only called in the constructor and nowhere else. That means, when your mystr is updated, the widget will not be aware of it. It does not work like you seem to expect; it is not a one-time property binding so that the widget will be be notified automatically and transparently when the string changes. You have to do that work on your own.
Beside, you really ought to aim for using QtNetwork in a Qt based client rather than platform specific POSIX API with BSD sockets.

openGL - issue when getting data via socket in glutTimerFunc

I am using UDP socket to send data to my openGL application. the openGL app should listent to the UDP socket in the glutTimerFunc callback and update the view according to the received data.
my main function:
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutCreateWindow("test");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutTimerFunc(1000, listenToUDP, 0); // here!
glClearColor(0,0,0,1);
glutMainLoop();
return 0;
}
my glutTimerFunc callback, which listens to the UDP socket:
void listenToUDP(int = 0)
{
int sockfd,n;
struct sockaddr_in servaddr,cliaddr;
socklen_t len;
char mesg[1000];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(32000);
bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
len = sizeof(cliaddr);
printf("1");
// here is the problem !!
n = recvfrom(sockfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&len);
printf("2");
sendto(sockfd,mesg,n,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
printf("-------------------------------------------------------\n");
mesg[n] = 0;
printf("Received the following:\n");
printf("%s",mesg);
printf("-------------------------------------------------------\n");
map<string, float> info = parseInfo(mesg);
scaleX += info.find("x") -> second;
printf("%f", scaleX);
glutPostRedisplay();
glutTimerFunc(1000, listenToUDP, 0);
}
when the first time I sent data to the application, it worked great. it waited for the data on the line I marked, and it printed everything and updated the view accordingly after I sent data to it.
However, it didn't work since the second time I sent data to it. it would print "1" but never print "2", which means it suspended on the line I marked. of course it would not update the view, either.
I am sure the UDP listener works well if it's independent(run it with an infinite loop), so I guess it's a problem related to the glutTimerFun. However, I totally have no idea.
my question is:
1) what's the reason for this behavior?
2) how can I fix it?
Please use & operator to get the address of function.
glutTimerFunc(1000, &listenToUDP, 0);
Please also remember to close the socket after using it every time:
close(sockfd);

Experiencing timeouts after connecting to 20 different servers using QTcpSocket

I've been experiencing a weird problem using QTcpSocket, I've searched the web but can't find anybody else with the same problem.
I have two bare-bones applications, one client and one server, if I run them both on my local machine the client successfully makes all 50 connections to the server.
If I run the server on another computer connected to the network (let's say: 10.1.1.1) it will again connect every time without a problem.
Now, if I change the server's main.cpp to initialise multiple servers under different ports (8001 to 8050), and change the client to make one connection to each server. With both running locally it still works fine.
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
for (int i = 8001; i <= 8050; ++i) {
Server server(i);
return app.exec();
}
}
But, if I put the server on 10.1.1.1 and try it again then I connect to the first 20 without a problem, but then it hangs for a while (anywhere upwards of 5 seconds) before connecting to the next 20, and so on until all are connected.
As a final test, I put an instance of the server on another machine (10.1.1.2) and created 15 instances of a server on each machine and tried to connect to both I experienced the same problem. All 15 of the first machine connected fine, as did the next 5 of the 2nd machine before it hung until eventually connecting to the last 10.
This is on Qt version 4.7.2. And I've experienced this problem on Fedora 17, Windows 7 but not Scientific Linux 6.
The code for the client/server is included below, I removed all the includes to save some vertical space:
Client
client.h
class Client: public QObject {
Q_OBJECT
public:
Client(QObject* parent = 0);
~Client();
void start(QString address, quint16 port);
public slots:
void startTransfer();
void disconnect() { qDebug("disconnect"); }
private:
QTcpSocket client;
};
client.cpp
Client::Client(QObject* parent): QObject(parent) {
connect(&client, SIGNAL(connected()), this, SLOT(startTransfer()));
connect(&client, SIGNAL(disconnected()), this, SLOT(disconnect()));
}
Client::~Client() {
client.close();
}
void Client::start(QString address, quint16 port) {
QHostAddress addr(address);
qDebug(QString("connecting to %1:%2").arg(address, QString::number(port)).toLocal8Bit().constData());
client.connectToHost(addr, port);
}
void Client::startTransfer() {
qDebug("connected");
client.write("Hello, world", 13);
}
main.cpp
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
for (int i = 0; i < 50; i++) {
Client *client = new Client;
client->start("192.168.0.1", 8888);
}
return app.exec();
}
Server
server.h
class Server: public QObject {
Q_OBJECT
public:
Server(int port = 8888, QObject * parent = 0);
~Server();
public slots:
void acceptConnection();
void startRead();
private:
QTcpServer server;
QList<QTcpSocket *> clients;
};
server.cpp
Server::Server(int port, QObject* parent): QObject(parent) {
qDebug(qPrintable("new server instance on port " + QString::number(port)));
connect(&server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
server.listen(QHostAddress::Any, port);
}
Server::~Server() {
server.close();
}
void Server::acceptConnection() {
QTcpSocket *client = server.nextPendingConnection();
clients.append(client);
connect(client, SIGNAL(readyRead()), this, SLOT(startRead()));
}
void Server::startRead() {
QTcpSocket *client = dynamic_cast<QTcpSocket *>(sender());
char buffer[1024] = {0};
client->read(buffer, client->bytesAvailable());
QString response = QString("%2 on server %3").arg(buffer, QString::number(server.serverPort()));
std::cout << qPrintable(response) << std::endl;
client->close();
}
main.cpp
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
Server server;
return app.exec();
}