server端
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> void server(int sock){ //1、建立接收缓存字节数组 char recvbuf[1024] = {0}; //2、定义socket struct sockaddr_in peeraddr; socklen_t peerlen; int n; while(1){ // peerlen = sizeof(peeraddr); //3、清空接收缓存数组 memset(recvbuf, 0, sizeof(recvbuf)); //4、开始接收数据 n = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&peeraddr, &peerlen); //5、判断是否接收完整数据 if(n == -1){ perror("recvfrom"); exit(EXIT_FAILURE); }else if(n > 0){ //6、成功接收数据,将缓存数据写入到标准输出,打印到控制台 fputs(recvbuf, stdout); //7、想客户端回送接收到的数据(回显客户端输入的数据) sendto(sock, recvbuf, n, 0, (struct sockaddr *)&peeraddr, peerlen); } } //关闭socket close(sock); } int main(void){ int sock; //创建服务器socket if((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0){ perror("socket error"); exit(EXIT_FAILURE); } //设置服务器socket参数 struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); //设置socket的协议、端口以及地址 servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //将socket绑定地址 if(bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){ perror("bind error"); exit(EXIT_FAILURE); } server(sock); return 0; }
client端
#include <unistd.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> void client(int sock){ //2、设置客户端socket参数 struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); //3、设置传输协议、端口以及目的地址 servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //4、创建发送与接收缓存字节数组 int ret; char sendbuf[1024] = {0}; char recvbuf[1024] = {0}; //5、开始发送数据(此处是发送来自标准输入的数据) while(fgets(sendbuf, sizeof(sendbuf), stdin) != NULL){ sendto(sock, sendbuf, strlen(sendbuf), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)); //6、开始接收数据,接收服务端返回的数据 ret = recvfrom(sock, recvbuf, sizeof(recvbuf), 0, NULL, NULL); if(ret == -1){ perror("recvfrom"); exit(EXIT_FAILURE); } //fputs(recvbuf, stdout); //将服务端返回的数据写入到标准输出 //7、清空发送与接收缓存 memset(sendbuf, 0, sizeof(sendbuf)); memset(recvbuf, 0, sizeof(recvbuf)); } //8、关闭socket流 close(sock); } int main(void){ int sock; //1.创建客户端的socket if((sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0){ perror("socket"); exit(EXIT_FAILURE); } client(sock); return 0; }
参考:http://www.cnblogs.com/skyfsm/p/6287787.html?utm_source=itdadao&utm_medium=referral
http://blog.csdn.net/chenlycly/article/details/51582257