PDA

View Full Version : Send a Qstring into different computers connected in a network.



mebingj
6th March 2011, 13:34
i want to send a string into different computers connected in a network.
i developed a program,where i can enter the IP addresses of the systems, to which the string is to be send.There is a client and a server program. The client is running only at the system which is sending the string and server is running at all other systems. But the client program is only sending the string to the system whose IP address is entered first.Please HELP!!


Client Code:


void resoadv::on_pushButton_3_clicked()
{
QString l,h;
QFile fi("ipreso.txt");
fi.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream(&fi);
while(!fi.atEnd())
{
h=stream.readLine();
sock->connectToHost(h, 40000);
QFile f("resoadv.txt");
f.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream1(&f);
l=stream1.readLine();
f.close();
//ui->label_3->setText(l);
QByteArray block = "";
block.append(l);
const char *str = l.toLatin1();
cout<<str;
sock->write(block);
sock->close();
sock->disconnectFromHost();
}
QFile file("ipreso.txt");
file.open(QIODevice::WriteOnly);
file.close();
}




server code:


#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Set up connection
server = new QTcpServer(this);

// If server does not listen
if( !server->listen(QHostAddress::Any,40000))
{

server->close();
return; // Leave constructor, e.g. if port is currently used
}
connect(server, SIGNAL(newConnection()), this, SLOT(on_new_connection()));
}

MainWindow::~MainWindow()
{
//delete ui;
server->close();
}

void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
//ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::on_new_connection()
{
sock = server->nextPendingConnection();
connect(sock, SIGNAL(readyRead()), this, SLOT(on_ready_read()));
}

void MainWindow::on_ready_read()
{
QByteArray msg=sock->readAll();
//sock->close();
QString message(msg);
ui->label->setText(message);
const char *m = message.toLatin1();
system(m);
}

squidge
6th March 2011, 13:44
1) Use signals and slots. This will ensure each stage is complete before starting the next stage.

2) Please use code tags when pasting code.

3) UDP may be better - you can then broadcast your string once and all the interested parties can receive it rather than connecting to each host individually.

4) Don't assume you'll receive the entire string in one go. You should append the string to a buffer until you know you have received all the text (ie, place a marker in the text somewhere or packetise your data so you know the expected length)