标签:class ems address recv 关闭 core 描述 code append
UDP无连接通信
s.sin_family = AF_INET; //IPV4协议族
s.sin_port = htons(8888); //端口号
s.sin_addr.s_addr = INADDR_ANY; //默认地址0x00000000
绑定端口
这个套接字有了本地IP,端口,通信协议
接收客户端发来的信息
1 ~ 6 的步骤与服务端相同
? 参考:UDP简单实战
//服务端:接收
int main()
{
struct sockaddr_in s; //定义套接字
int sock; //定义文件表述符
char buff[182]; //缓冲数组
if((sock = socket(AF_INET, SOCK_DGRAM, 0))==-1)
perror("error");
memset(&s,0,sizeof(s)); //刷新
s.sin_family = AF_INEF;
s.sin_port = htons(8888);
s.sin_addr.s_addr = INADDR_ANY;
if( bind(sock, (struct sockaddr *)&s, sizeof(s)) == -1 )
perror("error");
int sock_len = sizeof(s);
recvfrom( sock, buff, sizeof(buff)-1, 0, (struct sockaddr *)&s, &sock_len);
printf("message:%s", buff);
return 0;
}
//客户端:发送
int main()
{
struct sockaddr_in s; //定义套接字
int sock; //定义文件表述符
char buff[182]; //缓冲数组
if((sock = socket(AF_INET, SOCK_DGRAM, 0))==-1)
perror("error");
memset(&s,0,sizeof(s)); //刷新
s.sin_family = AF_INEF;
s.sin_port = htons(8888);
s.sin_addr.s_addr = INADDR_ANY;
scanf("%s", buff); //对字符串进行赋值
sendto(sock, buff, strlen(buff), 0, (struct sockaddr *)&s, sizeof(s));
return 0;
}
UDP通信需要的因素:
加入network环境:在core gui后面加入 network
QT += core gui network
udpsocket=new QUdpSocket(this); //新建一个套接字socket
/* 绑定本机端口号,允许其他服务器绑定同样的IP和端口,即使改地址被另外一个套接字绑定也应该重新绑定 */
udpsocket->bind((quint16)51303, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
connect(udpsocket,SIGNAL(readyRead()),this,SLOT(recvMsg())); // 发起连接
/* 关闭UDP */
udpsocket -> close();
/* 接收信息 */
void MainWindow::recvMsg(){
if(udpsocket->hasPendingDatagrams()){
QByteArray datagram;
datagram.resize(udpsocket->pendingDatagramSize());
udpsocket->readDatagram(datagram.data(),datagram.size());
ui->listWidget->insertItem(0,datagram);
}
}
QHostAddress addr("192.168.1.100"); //目标地址
QByteArray msg;
msg.append(ui->lineEdit->text()); //发送信息内容
udpsocket->writeDatagram(msg,addr,(quint16)51303); //发送目标机的地址和端口号
加入UDP头文件
#include <QUdpSocket>
公共成员声明
public:
QUdpSocket *udpsocket;
增加声明一个private slots
private slots:
void recvMsg();
? 参考:写个小小的UDP客户端
标签:class ems address recv 关闭 core 描述 code append
原文地址:https://www.cnblogs.com/fydream/p/13379935.html