if you need a socket, you have two options:
1.Instantiate QTcpSocket or QUdpSocket //实例化
2.Create a native socket descriptor, instantiate QAbstractSocket, and call setSocketDescriptor() to wrap the native socket.
Internally 1.在内部,内存 internally 1.在内(部) 2.内部的
QUdpSocket的连接两种方式:
1.void QAbstractSocket::connectToHost ( const QString & hostName, quint16 port, OpenMode openMode = ReadWrite )
例:udpSocket->connectToHost("211.87.147.238",6666,QIODevice::ReadWrite);
或udpSocket->connectToHost("example.com",6666,QIODevice::ReadWrite);
2.void QAbstractSocket::connectToHost ( const QHostAddress & address, quint16 port, OpenMode openMode = ReadWrite )
例:
QHostAddress *hostaddr;
hostaddr= new QHostAddress("211.87.147.238");//主机IP
udpSocket->connectToHost(*hostaddr,6666,QIODevice::ReadWrite);
连接源代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QHostAddress>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
udpSocket=new QUdpSocket();
//QHostAddress *hostaddr;
//hostaddr= new QHostAddress("211.87.147.238");//主机IP
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(pushButton_clicked()));
connect(udpSocket,SIGNAL(hostFound()),this,SLOT(hasfindhost()));//先查看host是否存在
connect(udpSocket,SIGNAL(connected()),this,SLOT(hasconnected()));//判断如果连接上
connect(udpSocket,SIGNAL(disconnected()),this,SLOT(hasnotconnected()));//如果断开连接
connect(udpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(erro()));//显示错误
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::hasfindhost()
{
qDebug()<<"HAS FOND HOST";
}
void MainWindow::hasconnected()
{
qDebug()<<"has connected";
}
void MainWindow::hasnotconnected()
{
qDebug()<<"has not connected";
}
void MainWindow::pushButton_clicked()
{ QString string=ui->lineEdit->text();
udpSocket->connectToHost(string,6666,QIODevice::ReadWrite);
}
void MainWindow::erro()
{
qDebug()<<"AN erro";
QString string=udpSocket->errorString();//此处为错误打印
qDebug()<<string;
}