当前位置: 代码迷 >> QT开发 >> TCP的一个例子但通信不成功,该怎么处理
  详细解决方案

TCP的一个例子但通信不成功,该怎么处理

热度:106   发布时间:2016-04-25 04:46:00.0
TCP的一个例子但通信不成功
client.cpp
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::Widget)
{
  ui->setupUi(this);
  tcpSocket = new QTcpSocket(this);
  connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage()));
  connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
  this,SLOT(displayError(QAbstractSocket::SocketError)));
  connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(on_pushButton_clicked()));

}

Widget::~Widget()
{
  delete ui;
}

void Widget::newConnect()
{
  blockSize = 0; //初始化其为0

  tcpSocket->abort(); //取消已有的连接

  /* tcpSocket->connectToHost(ui->hostLineEdit->text(),

  ui->portLineEdit->text().toInt());*/

  tcpSocket->connectToHost("192.168.1.24",6666);
  //连接到主机,这里从界面获取主机地址和端口号

}

void Widget::readMessage()

{

  QDataStream in(tcpSocket);

  in.setVersion(QDataStream::Qt_4_7);

  //设置数据流版本,这里要和服务器端相同

  if(blockSize==0) //如果是刚开始接收数据

  {

  //判断接收的数据是否有两字节,也就是文件的大小信息

  //如果有则保存到blockSize变量中,没有则返回,继续接收数据

  if(tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return;

  in >> blockSize;

  }

  if(tcpSocket->bytesAvailable() < blockSize) return;

  //如果没有得到全部的数据,则返回,继续接收数据

  in >> message;

  //将接收到的数据存放到变量中

  ui->messageLabel->setText(message);

  //显示接收到的数据

}

void Widget::displayError(QAbstractSocket::SocketError)

{

  qDebug() << tcpSocket->errorString(); //输出错误信息

}
void Widget::on_pushButton_clicked() //连接按钮

{

  newConnect(); //请求连接

}




server.cpp
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
  QWidget(parent),
  ui(new Ui::Widget)
{
  ui->setupUi(this);
  tcpServer = new QTcpServer(this);

  if(!tcpServer->listen(QHostAddress::LocalHost,6666))

  { //监听本地主机的6666端口,如果出错就输出错误信息,并关闭

  qDebug() << tcpServer->errorString();

  close();

  }
  connect(tcpServer,SIGNAL(newConnection()),this,SLOT(sendMessage()));

}

Widget::~Widget()
{
  delete ui;
}

void Widget::sendMessage()

{

  QByteArray block; //用于暂存我们要发送的数据

  QDataStream out(&block,QIODevice::WriteOnly);

  //使用数据流写入数据

  out.setVersion(QDataStream::Qt_4_7);

  //设置数据流的版本,客户端和服务器端使用的版本要相同

  out<<(quint16) 0;

  out<<tr("hello Tcp!!!");

  out.device()->seek(0);

  out<<(quint16)(block.size()-sizeof(quint16));

  QTcpSocket *clientConnection = tcpServer->nextPendingConnection();

  //我们获取已经建立的连接的子套接字

  connect(clientConnection,SIGNAL(disconnected()),clientConnection,

  SLOT(deleteLater()));

  clientConnection->write(block);

  clientConnection->disconnectFromHost();

  ui->statusLabel->setText("send message successful!!!");
  相关解决方案