UDP是一种无连接协议。客户端和服务器之间没有建立连接。这里讨论创建标准UDP客户端/服务器
先决条件: C / CPP中的套接字编程UDP服务器-客户端实现
在UDP中,客户端不像TCP中那样与服务器建立连接,而是仅发送数据报。同样,服务器不需要接受连接,而只是等待数据报到达。我们可以在UDP中调用一个名为connect()的函数,但不会像在TCP中那样产生任何结果。没有3种方式的握手。它只是检查是否有立即出现的错误,并存储对等方的IP地址和端口号。 connect()存储对等地址,因此无需在sendto()中传递服务器地址和服务器地址长度参数。
必要功能:
int connect(int sockfd, const struct sockaddr *servaddr,
socklen_t addrlen);
returns : 0 if OK -1 on error
arguments :
sockfd : File descriptor of socket to be connected.
struct sockaddr *servaddr : server address structure.
addrlen : length of server address structure.
以下是显示服务器-客户端之间的消息传输的实现:
UDP服务器代码:
// server program for udp connection
#include
#include
#include
#include
#include
#include
#define PORT 5000
#define MAXLINE 1000
// Driver code
int main()
{
char buffer[100];
char *message = "Hello Client";
int listenfd, len;
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof(servaddr));
// Create a UDP Socket
listenfd = socket(AF_INET, SOCK_DGRAM, 0);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// bind server address to socket descriptor
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
//receive the datagram
len = sizeof(cliaddr);
int n = recvfrom(listenfd, buffer, sizeof(buffer),
0, (struct sockaddr*)&cliaddr,&len); //receive message from server
buffer[n] = '\0';
puts(buffer);
// send the response
sendto(listenfd, message, MAXLINE, 0,
(struct sockaddr*)&cliaddr, sizeof(cliaddr));
}
UDP客户端代码:
// udp client driver program
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 5000
#define MAXLINE 1000
// Driver code
int main()
{
char buffer[100];
char *message = "Hello Server";
int sockfd, n;
struct sockaddr_in servaddr;
// clear servaddr
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// create datagram socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// connect to server
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("\n Error : Connect Failed \n");
exit(0);
}
// request to send datagram
// no need to specify server address in sendto
// connect stores the peers IP and port
sendto(sockfd, message, MAXLINE, 0, (struct sockaddr*)NULL, sizeof(servaddr));
// waiting for response
recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)NULL, NULL);
puts(buffer);
// close the descriptor
close(sockfd);
}
输出:
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。