PDA

View Full Version : Some issues with chat program



SIFE
25th May 2011, 00:09
I created a simple chat program based in client/server model using TCP of course. I have some issues starting from server ending to client, here is the list:
The server can't bind in specified address or port, I used lineEdit widgets to that, i tried to convert to int, but it doesn't work.
The server can send messages but it can't receive messages, even peer information like address.
If I clicked in connectButton widget, the client crash(I didn't test other functionality because the client crash before I did).
6470

Santosh Reddy
25th May 2011, 05:28
Hi SIFE, here you go.

You have two main problems in you code (both in server and client), but don't worry you have done most of it, all the problems are small, may be you just need figure things out

1. Both in server and client project, the "GuiClient", and "GuiServer" classes, are multiple inherited from QMainWindow, and Ui:GuiServer/Ui::GuiClient. You also have a member variable as Ui:GuiServer*/Ui::GuiClient* ui. This is not good, you already have ui instance from the inherited call Ui:GuiServer/Ui::GuiClient

Fix: You either have Ui:GuiServer/Ui::GuiClien as a base class (or) have ui as a member variable, but not both. This was the main problem. You tried to do a new Ui:GuiServer/Ui::GuiClien in the constructor, and then use the setupUi(), which is actually calling the base class method (you should be calling ui->setupUi(this)).

So just have only one the things, having both is not good.

2. In server code, you are trying to override (re-implement) incomingConnection() (which is a virtual member of QTcpServer), this will not work as GuiServer is not a sub-class of QTcpServer.

Fix: The better way would be to make incomingConnection(), as a slot in GuiServer, and connect server.newConnection() signal to this.incomingConnection(), as shown below, also modify the GuiServer::incomingConnection() accordingly.



void GuiServer::startServer()
{
//bool stat = server->listen(QHostAddress::Any, quint16(portEdit->text().toUShort()));
bool stat = server->listen(QHostAddress::Any, 5000);
qDebug("%d", stat);
/* if(!stat)
QMessageBox::critical(this, "Error to bind port", "Fail to listen");
else
{
startButton->setEnabled(false);
stopButton->setEnabled(false);
}
*/
connect(server, SIGNAL(newConnection()), this, SLOT(incomingConnection())); //Added
}

void GuiServer::incomingConnection(void)
{
QTcpSocket *client = server->nextPendingConnection(); //modified

qDebug() << "New client from:" << client->peerAddress().toString();

connect(client, SIGNAL(readyRead()), this, SLOT(readMsg()));
connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMsg()));
connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
}


With these changes, I was able to send text form client to server. I guess you can carry on from here

Good Luck.

SIFE
26th May 2011, 01:12
Now my problem solved.