用C++写一个UDP通信程序,分为客户端和服务端
时间: 2023-09-30 09:01:47 浏览: 123
以下是一个简单的UDP通信程序,包括了客户端和服务端的代码:
服务端:
```c++
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
const int BUF_SIZE = 1024;
int main(int argc, char* argv[])
{
if(argc != 2)
{
cout<<"Usage: "<<argv[0]<<" <port>"<<endl;
exit(1);
}
int serv_sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[1]));
bind(serv_sock, (sockaddr*)&serv_addr, sizeof(serv_addr));
sockaddr_in clnt_addr;
socklen_t clnt_addr_len = sizeof(clnt_addr);
char buffer[BUF_SIZE];
while(true)
{
int str_len = recvfrom(serv_sock, buffer, BUF_SIZE, 0, (sockaddr*)&clnt_addr, &clnt_addr_len);
sendto(serv_sock, buffer, str_len, 0, (sockaddr*)&clnt_addr, clnt_addr_len);
}
close(serv_sock);
return 0;
}
```
客户端:
```c++
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
const int BUF_SIZE = 1024;
int main(int argc, char* argv[])
{
if(argc != 3)
{
cout<<"Usage: "<<argv[0]<<" <IP> <port>"<<endl;
exit(1);
}
int clnt_sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(atoi(argv[2]));
while(true)
{
char message[BUF_SIZE];
cout<<"Enter message to send: ";
cin>>message;
sendto(clnt_sock, message, strlen(message), 0, (sockaddr*)&serv_addr, sizeof(serv_addr));
sockaddr_in from_addr;
socklen_t from_addr_len = sizeof(from_addr);
char buffer[BUF_SIZE];
int str_len = recvfrom(clnt_sock, buffer, BUF_SIZE, 0, (sockaddr*)&from_addr, &from_addr_len);
buffer[str_len] = 0;
cout<<"Message from server: "<<buffer<<endl;
}
close(clnt_sock);
return 0;
}
```
这个程序简单地实现了一个服务端和客户端之间的UDP通信。服务端接收来自客户端的消息,然后将其原封不动地发送回客户端。客户端循环地读取用户输入并将其发送到服务端,然后等待来自服务端的响应。
阅读全文