CSocket::Create() returns 0 - mfc

I've connecting other process with socket connecting. So I create client socket which is object of CSocket Class. And I call Create method in CSocket class and I make my own program. But It doesn't work in create. It returns 0 value. Please tell me why does this happens.
Here's my brief code
CSocket *socket = new CSocket();
if(socket->Create())
if(socket->Connect("127.0.0.1",0))
socket->Send(widthCap, sizeof(widthCap));
socket->Close();
Thank you

Call GetLastError() and look the value up here. I would guess that you have a firewall that blocks your exe. Remember that adding your exe to your firewall exception list will not help as you probably build a new exe every time you hit F5.

Related

How do I (gracefully) terminate a gSOAP server?

I have gSOAP server generated from a WSDL file + a Qt GUI. The generated code works perfectly fine, except one point that causes my process to stay alive after GUI exits. (I'm deploying on Windows, so I have no signaling)
I need my GUI to stay alive (naturally) so I moved server-proxy object to a QObject-based class that the latter is moved to another QThread, and the I fire it up by an external signal. The server now runs on event-loop of its parent QObject and works fine.
The only problem is that I have no clue how to terminate server on exit. I tried tweaking generated code for server (is that really a good idea by the way?)
int MySweetService::run(int port)
{ if (!soap_valid_socket(this->soap->master) && !soap_valid_socket(this->bind(NULL, port, 100)))
return this->soap->error;
for (;;) // =====> Maybe here I can put my while(module_is_running_atomic_bool) ?
{ if (!soap_valid_socket(this->accept()))
{ if (this->soap->errnum == 0) // timeout?
this->soap->error = SOAP_OK;
break;
}
if (this->serve())
break;
this->destroy();
}
return this->soap->error;
}
Calling soap_done(&soap) from another thread terminates blocking call to accept() and next your "serving" thread. It works for me on Windows but I doesn't on Linux - it looks like gsoap has some multitasking issue. You also need some boolean flag to let "serving" thread know that you shut it down and it's not just error in gsope.

Can i use QTcpSocket again for another connection after deleteLater?

I try to use QTcpSserver, which would keep connection with one and only one client at a time, until the client disconnects. So, I keep the client with a member pointer in my class.
The problem arises here: In the examples I see on the internet, after disconnected(), it is called deleteLater(). Good, but I would use this class-member pointer again for another connection. Remember that the server keeps one and only one client at a time. So, what if the socket object is deleted after another connection assigned on it?
What I mean is:
class TcpServer(QObject* o) : public QTcpServer {
...
private:
QTcpSocket* client;
}
void TcpServer::connected() {
client = this->nextPendingConnection();
this->pauseAccepting();
connect(client, SIGNAL(disconnected()), client, SLOT(clientDisconnected()));
}
void TcpServer::clientDisconnected() {
client->deleteLater();
this->resumeAccepting();
}
Scenario is this:
Client connected. So, client = nextPendingConnection();
Server paused listening. Does not accept new connection.
Client is disconnected. client needs to be released. So, client->deleteLater() is calleed.
Server continues listening.
New connection comes. So, I need to client = nextPendingConnection();
But, previous client object was deleted? Maybe? Maybe not? What if event loop tries to delete client, after I have assigned the new connection to it in step 5?
So, how would I keep one and only one client, while deleting previous disconnected ones?
Would it be safe if I do this?
void TcpServer::clientDisconnected()
{
QSocket* ptr = client;
ptr->deleteLater();
...
}
I will cite Qt documentation about it:
The object will be deleted when control returns to the event loop.
So deleteLater() is a delayed delete. The object is to be regarded as deleted as soon as the call deleteLater() was made.
Your nextPendingConnection() call will create another object that need to be deleted some time later.
However in your case you only allow one pending connection as you said and disallow accepting until client gets disconnected. I this case it should be safe, in other cases you could overwrite your client pointer and will lose control over it (memory leak).
Even in your case, I would prefer this solution:
void TcpServer::clientDisconnected()
{
if (qobject_cast<QAbstractSocket*>(sender())) {
sender()->deleteLater();
}
...
}
This would also be safe if more than one connection is allowed in future changes of your application.
As i understand nextPendingConnection(); will return pointer to new QTcpSocket class object so you have nothing to worry about.
deleteLater() will scheduled for deletion only your old object. QTcpSocket* client contains only pointer to QTcpSocket class object. When you calling deleteLater() Qt will delete only object to which client was pointed at time of calling this function.

c++ ptlib PNotifier use in OPAL

I'm using OpalVoip for making a softphone application and i got stuck with following:
void MyManager::main()
{
//variables
PNotifier notify; // this is the problem
//it is the template PNotifierFunctionTemplate<INT>
//more stuff
listener->Open(notify);
//listener is of type OpalListenerUDP
//it should start the listener and wait for incoming connection
//but however i need to pass this NOTIFY which should be the INT parameter to the
//new OpalTransport instance created by the listener...
//however OpalListenerUDP only creates OpalTransport after the connection is
//accepted as so in following: OpalListenerUDP::Accept(/*time interval*/)
//
//So far I think that this notifier should be a pointer to an object of type
//OpalListenerUDP but i have no idea how to get it done
}
Any help will be appreciated, Red.
After deeper research into opal source code, I've found the solution.
It turns out that
OpalConnection::StartListener(OpalListener&);
Will do the job of opening listener, so there is no need of calling OpalListener::Open() so after it is only needed to call OpalListener::Accept to accept a connection.

QTcpSocket and deletion

I'm writing a tcp based server using Qt.
I plan this server to be multithreaded,
so my tcpserver class inherits from QTcpServer and overrides incomingConnection(). Everything is fine, except when it comes to deleting a user.
The TcpServer class manages
a list of QSharedPointer<Client>. When I remove the said client from the list, it gets automatically deleted because of the smart pointer.
My Client class owns a QSharedPointer<QTcpSocket> which means that the client's
QTcpSocket gets deleted when the client is deleted.
Problem is, it seems that Qt tries to use this socket after its deletion, causing Segmentation Fault.
Should I manages a list for the sockets only, and call deleteLater() on them when I dont need them anymore?
Or should I switch my socket's pointer in client class to a normal pointer?
void SlotSocketError(void)
{
QTcpSocket sock = qobject_cast<QTcpSocket *>(QObject::sender());
QSharedPointer<Client> client = GetClientFromSocket(sock);
_clientList.removeAt(GetClientPositionInList(client));
}
QList<QSharedPointer<Client> > _clientsList; // From TcpServer header.
/* Client's class header */
QSharedPointer<QTcpSocket> _socket;
You need to use deleteLater on the Object. Incoming messages may come in after you delete the QTCPSocket. It is documented in Assistant. You can find an example here: qthelp://com.trolltech.qt.472/qdoc/qt4-network.html
M
When you create your QSharedPointers you can pass a deleter to them, so that they'll use deleteLater instead of delete when you remove them from the list.
There is an example that does exactly that in the documentation too:
http://doc.trolltech.com/latest/qsharedpointer.html#QSharedPointer-3

C++ MFC server app with sockets crashes and I cannot find the fault, help!

My program has one dialog and two sockets. Both sockets are derived from CAsyncSocket, one is for listening, other is for receiving data from client. My program crashes when client tries to connect to server application and server needs to initialize receiving socket.
This is my MFC dialog class.
class CFileTransferServerDlg : public CDialog
{
...
ListeningSocket ListenSock;
ReceivingSocket* RecvSock;
void OnAccept(); // called when ListenSock gets connection attempt
...
};
This is my derived socket class for receiving data that calls parent dialogs method when event is signaled.
class ReceivingSocket : public CAsyncSocket
{
...
CFileTransferServerDlg* m_pDlg; // for accessing parent dialogs controls
virtual void OnReceive(int nErrorCode);
...
}
ReceivingSocket::ReceivingSocket()
{
}
This is dialogs function that handles incoming connection attempt when listening socket gets event notification. This is where the crash happens.
void CFileTransferServerDlg::OnAccept()
{
RecvSock = new ReceivingSocket; /* CRASH */
}
OR
void CFileTransferServerDlg::OnAccept()
{
ReceivingSocket* tmpSock = new ReceivingSocket;
tmpSock->SetParentDlg(this);
CString message;
if( ListenSock.Accept(*tmpSock) ) /* CRASH */
{
message.LoadStringW(IDS_CLIENT_CONNECTED);
m_txtStatus.SetWindowTextW(message);
RecvSock = tmpSock;
}
}
My program crashes when I try to create a socket for receiving file sent from client application. OnAccept starts when Listening socket signals incoming connection attempt, but my application then crashes. What could be wrong?
Error in debug mode:
Unhandled exception at 0x009c30e1 in FileTransferServer.exe: 0xC0000005: Access violation reading location 0xccccce58.
UPDATE:
I edited code a little and I've found that inside sockcore.cpp where Accept is defined, program failes on this line of code:
ASSERT(rConnectedSocket.m_hSocket == INVALID_SOCKET);
I don't understand how that can happen. ReceivingSocket class is somehow not getting constructed right. I derive it from CAsyncSock, leave constructor empty, and no matter where I create it, on stack or on heap, it always crashes.
Here is complete project, both client and server, if anyone can take a look at it I would be really grateful. I apologize for the comments, they are in Croatian.
Visual Studio project
I've looked into your code. The issue seems to be that you never call ListeningSocket::SetParentDlg(CFileTransferServerDlg* parent). Since you also do not initialize the m_pDlg pointer in the ListeningSocket constructor, it has random values and the program might crash here and there when you access this pointer. (I had also a crash but slightly at another location than you pointed out.)
I've changed it this way:
In ListeningSocket.h changed the constructor:
ListeningSocket(CFileTransferServerDlg* parent);
Also in ListeningSocket.cpp:
ListeningSocket::ListeningSocket(CFileTransferServerDlg* parent)
: m_pDlg(parent)
{
}
Constructor of CFileTransferServerDlg changed this way:
CFileTransferServerDlg::CFileTransferServerDlg(CWnd* pParent /*=NULL*/)
: CDialog(CFileTransferServerDlg::IDD, pParent),
ListenSock(this)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
Crash disappeared.
Other ways are possible of course.
Really nice little programs, by the way :) I'll delete them of course now since I can't probably afford the license fees :)
Maybe check to see if you've inherited ReceivingSocket correctly?
Check this out.