单客户端和服务端的通信(基于UDP) 代码
服务端代码socket3.c
#include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<stdlib.h> #include<stdio.h> #include<string.h> #include<netdb.h> #include<errno.h> #define PORT 8888 #define MAX_MSG_SIZE 1024 int main(void) { int sockfd, addrlen, n; struct sockaddr_in addr; char msg[MAX_MSG_SIZE]; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { fprintf(stderr, "socket failed "); exit(EXIT_FAILURE); } addrlen = sizeof(struct sockaddr_in); bzero(&addr, addrlen); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(PORT); if (bind(sockfd, (struct sockaddr*)(&addr), addrlen) < 0) { fprintf(stderr, "bind fail "); exit(EXIT_FAILURE); } puts("bind success"); while (1) { bzero(msg, MAX_MSG_SIZE); n = recvfrom(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)(&addr), &addrlen); fprintf(stdout, "Recevie message from client is %s ", msg); fgets(msg, MAX_MSG_SIZE,stdin); printf("Server endpoint input message %s ", msg); sendto(sockfd, msg, n, 0,(struct sockaddr *)(&addr), addrlen); } close(sockfd); exit(EXIT_SUCCESS); }
客户端代码socket4.c
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #define MAX_BUF_SIZE 1024 #define PORT 8888 int main() { int sockfd, addrlen, n; char buffer[MAX_BUF_SIZE]; struct sockaddr_in addr; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { fprintf(stderr, "socket falied "); exit(EXIT_FAILURE); } addrlen = sizeof(struct sockaddr_in); bzero(&addr, addrlen); addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = htonl(INADDR_ANY); puts("socket success"); while(1) { bzero(buffer, MAX_BUF_SIZE); fgets(buffer, MAX_BUF_SIZE, stdin); sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), addrlen); printf("client send msg is %s ", buffer); n = recvfrom(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), &addrlen); fprintf(stdout, "clinet Receive message from server is %s ", buffer); } close(sockfd); exit(0); return 0; }
运行结果截图如下:
5、总结
服务端:socket->bind->(sendto 、revcfrom)
客户端:socket->(sendto 、revcfrom)
upd不是面相连接的,这个是和tcp本质区别,数据可能会乱序,重复。