linux udp客户端及服务器
udpClient.c
#include #include #include #include #include #define BUF_SIZE 1400 void error_handling(char *message); int main(int argc, char *argv[]){ int sock; char message[BUF_SIZE] = {0}; int str_len; socklen_t addr_sz; struct sockaddr_in serv_addr, from_addr; sock=socket(PF_INET, SOCK_DGRAM, 0); //创建一个面向消息类型的套接字,注意第二个实参SOCK_DGRAM if(sock==-1) error_handling("socket() error"); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr("192.168.56.128"); serv_addr.sin_port=htons(8888); //----------------- FILE *fp = fopen(argv[1], "rb"); if (!fp) { return -1; } char buf[BUF_SIZE]; while(1) { bzero(buf,BUF_SIZE); int size = fread(buf, 1, sizeof(buf) - 1, fp); if (size > 0) { sendto(sock, buf, size, 0, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); } else { //文件读完了,重新开始 fseek(fp, 0, SEEK_SET); } } close(sock); return 0;} void error_handling(char *message){ fputs(message, stderr); fputc('\n', stderr); exit(1);}
udpService.c
#include #include #include #include #include #include #define SERVER_PORT 8888#define BUFF_LEN 1400#define SERVERIP "192.168.56.128"FILE *rfile = NULL; void handle_udp_msg(int fd){ char buf[BUFF_LEN] = {0}; //接收缓冲区,1024字节 socklen_t len; int count = 0; struct sockaddr_in clent_addr; //clent_addr用于记录发送方的地址信息 while(1) { memset(buf, 0, BUFF_LEN); len = sizeof(clent_addr); count = recvfrom(fd, buf, BUFF_LEN, 0, (struct sockaddr*)&clent_addr, &len); //recvfrom是拥塞函数,没有数据就一直拥塞 if(count > 0) { fwrite(buf,count,1,rfile); fflush(rfile); } if(count == -1) { printf("recieve data fail!\n"); return; } }} int main(int argc, char* argv[]){ rfile = fopen("recv.h265","wb"); int server_fd, ret; struct sockaddr_in ser_addr; server_fd = socket(AF_INET, SOCK_DGRAM, 0); //AF_INET:IPV4;SOCK_DGRAM:UDP if(server_fd < 0) { printf("create socket fail!\n"); return -1; } memset(&ser_addr, 0, sizeof(ser_addr)); ser_addr.sin_family = AF_INET; ser_addr.sin_addr.s_addr = htonl(INADDR_ANY); //IP地址,需要进行网络序转换,INADDR_ANY:本地地址 ser_addr.sin_port = htons(SERVER_PORT); //端口号,需要网络序转换 ret = bind(server_fd, (struct sockaddr*)&ser_addr, sizeof(ser_addr)); if(ret < 0) { printf("socket bind fail!\n"); return -1; } handle_udp_msg(server_fd); //处理接收到的数据 close(server_fd); return 0;}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~