[转]http://www.cnblogs.com/tornadomeet/archive/2012/04/11/2442140.html
使用Linux Socket做了小型的分布式,如Linux C Socket编程原理及简单实例。
为了更好地分布也得看看Win Socket。
Win Socket TCP原理图:
Win Socket UDP原理图:
简单TCP连接实例:
服务器端:
1 #include <WINSOCK2.H> 2 #include <stdio.h> 3 #pragma comment(lib,"ws2_32.lib") 4 int main(int argc,char **argv) 5 { 6 ///创建套接字 7 WORD myVersionRequest; 8 WSADATA wsaData; 9 myVersionRequest=MAKEWORD(1,1); 10 int err; 11 err=WSAStartup(myVersionRequest,&wsaData); 12 if (!err){ 13 printf("已打开套接字\n"); 14 }else{ 15 printf("ERROR:嵌套字未打开!"); 16 return 1; 17 } 18 19 ///进一步绑定套接字 20 SOCKET serSocket=socket(AF_INET,SOCK_STREAM,0);//创建了可识别套接字 21 22 ///需要绑定的参数 23 SOCKADDR_IN addr; 24 addr.sin_family=AF_INET; 25 addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//ip地址 26 addr.sin_port=htons(6000);//绑定端口 27 28 bind(serSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));//绑定完成 29 listen(serSocket,5);//其中第二个参数代表能够接收的最多的连接数 30 31 ////////////////////////////////////////////////////////////////////////// 32 //开始进行监听 33 ////////////////////////////////////////////////////////////////////////// 34 SOCKADDR_IN clientsocket; 35 int len=sizeof(SOCKADDR); 36 while (1) 37 { 38 SOCKET serConn=accept(serSocket,(SOCKADDR*)&clientsocket,&len);//如果这里不是accept而是conection的话。。就会不断的监听 39 char sendBuf[100]; 40 41 sprintf(sendBuf,"hello, %s !",inet_ntoa(clientsocket.sin_addr));//找对对应的IP并且将这行字打印到那里 42 printf("Send:%s\n",sendBuf); 43 send(serConn,sendBuf,strlen(sendBuf)+1,0); 44 45 char receiveBuf[100];//接收 46 recv(serConn,receiveBuf,sizeof(receiveBuf),0); 47 printf("recv:%s\n",receiveBuf); 48 49 closesocket(serConn);//关闭 50 WSACleanup();//释放资源的操作 51 return 0; 52 } 53 return 1; 54 }
客户端:
1 #include <WINSOCK2.H> 2 #include <stdio.h> 3 #pragma comment(lib,"ws2_32.lib") 4 int main(int argc,char **argv) 5 { 6 int err; 7 WORD versionRequired; 8 WSADATA wsaData; 9 versionRequired=MAKEWORD(1,1); 10 err=WSAStartup(versionRequired,&wsaData);//协议库的版本信息 11 if (!err) { 12 printf("客户端嵌套字已经打开!\n"); 13 }else{ 14 printf("ERROR:客户端的嵌套字打开失败!\n"); 15 return 1;//结束 16 } 17 SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0); 18 19 SOCKADDR_IN clientsock_in; 20 clientsock_in.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); 21 clientsock_in.sin_family=AF_INET; 22 clientsock_in.sin_port=htons(6000); 23 24 connect(clientSocket,(SOCKADDR*)&clientsock_in,sizeof(SOCKADDR));//开始连接 25 char receiveBuf[100]; 26 if(true){ 27 28 printf("Send:%s\n","hello,this is client"); 29 send(clientSocket,"hello,this is client",strlen("hello,this is client")+1,0); 30 31 recv(clientSocket,receiveBuf,101,0); 32 printf("Recv:%s\n",receiveBuf); 33 34 closesocket(clientSocket); 35 WSACleanup(); 36 } 37 return 0; 38 }
执行如下:
服务器端:
客户端: