qt TCP 网络编程(1)

         TCP(Transmission Control protocol)是传输控制协议,在qt 文档中是这样描述它的,The QTcpSocket class provides a TCP socket.,TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. It is especially well suited for continuous transmission of data.(tcp是可靠的,面向流的,面向连接传输协力的,特别是适合一连串的传输数据。

       在这简单的说明一下,QTcpSocket,QTcpServer,这连个类,32 public functions inherited from QAbstractSocket,33 public functions inherited from QIODevice,29 public functions inherited from QObject,它继承了QIODevice,这个比较复杂,我不能一一介绍了,但我还说一下其中的注意点,QIODevice provides both a common implementation and an abstract interface for devices that support reading and writing of blocks of data,  QIODevice is abstract and can not be instantiated.QIODevice是一个抽象类,抽象类是含有纯虚函数的,所以他不能实例化.但是大家可以implement the interface,这感觉是java似的,我觉得qt是利用java的设计思想来设计c++,可以去qt文档看一下这个类!

     这说明QTcpSocket这个类很方便的,我再介绍一下其中几个函数,qint64 bytesAvailable(),Returns the number of bytes that are available for reading.它返回要读数据流的长度。qint64 bytesToWritten(),For buffered devices, this function returns the number of bytes waiting to be written. For devices with no buffer, this function returns 0.

    qint64 read(char*data,qin64 maxsize)

   Reads at most maxSize bytes from the device into data, and returns the number of bytes read. If an error occurs, such as when attempting to read from a device opened in WriteOnly mode, this function returns -1.    0 is returned when no more data is available for reading. However, reading past the end of the stream is considered an error, so this function returns -1 in those cases (that is, reading on a closed socket or after a process has died).

    QbyteArry read(qint64 maxSize)

  This is an overloaded function.Reads at most maxSize bytes from the device, and returns the data read as a QByteArray.

This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

   以上几个函数是QIODevice里面的。所以QTcpSocket很方便的,继承它,读写不是神马问题的! 我还得讲一下它里面的继承的QAbstractSocket里面的几个函数吧,

void connectToHost ( const QString & hostName, quint16 port, OpenMode openMode = ReadWrite )
void connectToHost ( const QHostAddress & address, quint16 port, OpenMode openMode = ReadWrite )

     Attempts to make a connection to hostName on the given port.就是连接服务器。

     SIGNALS

void connected ()
void disconnected ()

This signal is emitted after connectToHost() has been called and a connection has been successfully established.

This signal is emitted when the socket has been disconnected.

 这连信号不用你管,但是你了解这两个对tcp网络编程流程好处!其他自己了解吧!下面我会给个连接。点击打开链接

  还有它本身特有的功能,sianal

void QIODevice::readyRead () [signal]

This signal is emitted once every time new data is available for reading from the device. It will only be emitted again once new data is available, such as when a new payload of network data has arrived on your network socket, or when a new block of data has been appended to your device.

 接下来,我介绍QTcpSever ,大家不要急,到后面我给出一个简单的列子!

bool QTcpServer::listen ( const QHostAddress & address = QHostAddress::Any, quint16 port = 0 )

     这个用于监的, Tells the server to listen for incoming connections on address address and port port. If port is 0, a port is chosen automatically. If address isQHostAddress::Any, the server will listen on all network interfaces.

QTcpSocket * QTcpServer::nextPendingConnection () [virtual]

   

 Returns the next pending connection as a connected QTcpSocket object.

The socket is created as a child of the server, which means that it is automatically deleted when the QTcpServer object is destroyed. It is still a good idea to delete the object explicitly when you are done with it, to avoid wasting memory.

0 is returned if this function is called when there are no pending connections.这哥用于生成QTcpSocket,用于服务器接收!

  因为我也刚学,不知道是连接就生成一个。

  SIGNAL

void QTcpServer::newConnection () [signal]


This signal is emitted every time a new connection is available.

 大概理论就这样!

 



 先编写服务器,建一个tcpserver.h

 #ifndef TCPSERVER_H

#define TCPSERVER_H
#include<QTcpServer>
class Chatserver : public QTcpServer
{
public:
    Chatserver();
    ~Chatserver();
protected:
private:
 
 
};
#endif // TCPSERVER_H
 

widget.h

#ifndef WIDGET_H

#define WIDGET_H
 
#include <QWidget>
#include"tcpserver.h"
#include<QTcpSocket>
namespace Ui {
    class Widget;
}
class Widget : public QWidget
{
    Q_OBJECT
 
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
protected:
protected slots:
    void aceeptconnect();
  void  readdata();
private:
    Ui::Widget *ui;
    Chatserver*chatserver;
    QTcpSocket*socket;
    int ld;
};
 
#endif // WIDGET_H
 tcpserver.cpp 

#include"tcpserver.h"

Chatserver::Chatserver(){
    listen(QHostAddress::LocalHost,7658);
}
Chatserver::~Chatserver(){
}
 widget.cpp 

#include<QVariant>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    chatserver=new Chatserver();
    connect(chatserver,SIGNAL(newConnection()),this,SLOT(aceeptconnect()));//当有新的连接的时候,就开始读数据
}
Widget::~Widget()
{
    delete ui;
}
void Widget::aceeptconnect()
{
socket=chatserver->nextPendingConnection();
connect(socket,SIGNAL(readyRead()),this,SLOT(readdata()));
}
void Widget::readdata(){
    char buf[1024]={0};
    socket->read(buf,socket->bytesAvailable());
    QVariant*temp=new QVariant(buf);
    ui->TargetWidget->addItem(temp->toString());
 
}
 
 main.cpp 

#include <QtGui/QApplication>

#include "widget.h"
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
 
    return a.exec();
}
再建一个widget的工程,名为client
在widget.h文件中
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTcpSocket>
namespace Ui {
    class Widget;
}
class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
protected slots:
   void send();
private:
    Ui::Widget *ui;
    QTcpSocket*client;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include<QTcpSocket>
#include<QHostAddress>
#include<QMessageBox>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    client=new QTcpSocket(this);
    client->connectToHost(QHostAddress::LocalHost,7658);
    connect(ui->Okbtn,SIGNAL(clicked()),this,SLOT(send()));//但按下按钮就发送
}
Widget::~Widget()
{
    delete ui;
}
void Widget::send(){
  if(client->write("hello",6)==-1)
      QMessageBox::warning(this,tr("wraning"),tr("this is warning"),QMessageBox::Yes);
}
main.cpp 不变!
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值