基礎知識
UDP和TCP的區別:
1、TCP是面向連接的,而UDP是非面向連接的,因此TCP更可靠
2、UDP的server端的socket不需要監聽
3、二者的server端都需要綁定
代碼實現:
Server端:
/************************************************************************* > File Name: server.c > Author: HonestFox > Mail: [email protected] > Created Time: Sun 24 Jul 2016 09:23:45 PM CST ************************************************************************/ #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<string.h> #include<unistd.h> #include<netinet/in.h> #include<stdlib.h> static void usage(const char *proc) { printf("usage : %s IP : %s\n", proc, proc); } int main(int argc, char *argv[]) { if( argc != 3) { usage(argv[0]); return 1; } int sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock < 0) { perror("socket"); exit(1); } //1.Create a Socket struct sockaddr_in local; local.sin_family = AF_INET; local.sin_port = htons(atoi(argv[2]) ); local.sin_addr.s_addr = inet_addr(argv[1]); //2.Bind if(bind(sock, (struct sockaddr*)&local, sizeof(local) ) < 0) { perror("bind error"); return 2; } //3.Receive & Send int done = 0; struct sockaddr_in peer; socklen_t len = sizeof(peer); char buf[1024]; while(!done) { memset(buf, '\0', sizeof(buf)); recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&peer, &len); printf("client: %s\n", buf); } return 0; }Client端:
/************************************************************************* > File Name: client.c > Author: HonestFox > Mail: [email protected] > Created Time: Sun 24 Jul 2016 09:23:41 PM CST ************************************************************************/ #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<string.h> #include<netinet/in.h> #include<unistd.h> #include<stdlib.h> static void usage(const char *proc) { printf("usage : %s IP : %s\n", proc, proc); } int main(int argc, char *argv[]) { if( argc != 3) { usage(argv[0]); return 1; } int sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock < 0) { perror("socket"); exit(1); } //1.Create a Socket struct sockaddr_in remote; remote.sin_family = AF_INET; remote.sin_port = htons(atoi(argv[2]) ); remote.sin_addr.s_addr = inet_addr(argv[1]); //2.No Need to Bind //3 Send & Receive int done = 0; struct sockaddr_in peer; socklen_t len = sizeof(peer); char buf[1024]; while(!done) { memset(buf, '\0', sizeof(buf)); printf("plz enter: "); fflush(stdout); ssize_t _s = read(0, buf, sizeof(buf) - 1); if(_s > 0) { buf[_s - 1] = '\0'; sendto(sock, buf, sizeof(buf), 0, (struct sockaddr*)&remote, sizeof(remote)); memset(buf, '\0', sizeof(buf)); } } return 0; }目前這段代碼 僅僅是 一端能不斷地向另一端發送數據,另一端會不斷接收。
要想像即時通訊軟件那樣實現聊天的功能,還在研究ing