请用C++写一段UDP通信,实现客户端发送消息,服务器响应
时间: 2024-03-03 14:48:45 浏览: 68
用C++编写UDP通信程序
4星 · 用户满意度95%
好的,下面是一段简单的UDP通信的示例代码:
客户端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
int sockfd, n;
char sendline[100], recvline[100];
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(9999);
while (fgets(sendline, 100, stdin) != NULL) {
sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
n = recvfrom(sockfd, recvline, 100, 0, NULL, NULL);
recvline[n] = '\0';
cout << "recv: " << recvline << endl;
}
return 0;
}
```
服务器端代码:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
int sockfd, n;
char recvline[100], sendline[100];
struct sockaddr_in servaddr, cliaddr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(9999);
bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
while (true) {
socklen_t len = sizeof(cliaddr);
n = recvfrom(sockfd, recvline, 100, 0, (struct sockaddr*)&cliaddr, &len);
recvline[n] = '\0';
cout << "recv: " << recvline << endl;
strcpy(sendline, "I got your message!");
sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
}
return 0;
}
```
运行这两个程序,然后在客户端输入消息,服务器会响应并返回一条固定的消息。
阅读全文