[C++] socket - 1 [简单TCP通信C\S代码]
服务端:
1 #include<iostream> 2 #include<winsock2.h> 3 #include<stdio.h> 4 #pragma comment(lib,"WS2_32.lib")//显示连接套接字库 5 int main() 6 { 7 WSADATA data;//定义WSADATA结构体 8 WORD w=MAKEWORD(2,0);//定义版本号 9 char sztext[]="Welcome you\r\n";//定义并初始化发送到客户端的字符数组 10 ::WSAStartup(w,&data);//初始化套接字库 11 SOCKET s,s1;//定义连接套接字和数据收发套接字句柄 12 s=::socket(AF_INET,SOCK_STREAM,0);//创建TCP套接字 13 sockaddr_in addr,addr2;//定义套接字地址结构 14 int n=sizeof(addr2); 15 addr.sin_family=AF_INET;//初始化地质结构 16 addr.sin_port=htons(75); 17 addr.sin_addr.S_un.S_addr=INADDR_ANY; 18 ::bind(s,(sockaddr*)&addr,sizeof(addr));//绑定套接字 19 ::listen(s,5);//监听套接字 20 printf("Server already start!\r\n"); 21 while(true) 22 { 23 s1=::accept(s,(sockaddr*)&addr2,&n);//接收连接请求 24 if(s1!=NULL) 25 { 26 printf("%s already connect\r\n",inet_ntoa(addr2.sin_addr)); 27 ::send(s1,sztext,sizeof(sztext),0);//向客户端发送字符数组 28 } 29 ::closesocket(s);//关闭套接字句柄 30 ::closesocket(s1); 31 ::WSACleanup();//释放套接字库 32 if(getchar()) 33 { 34 return 0; 35 } 36 else 37 { 38 ::Sleep(100); 39 } 40 } 41 }
客户端:
1 #include<iostream> 2 #include<winsock2.h> 3 #include<stdio.h> 4 #pragma comment(lib,"WS2_32.lib")//显示连接套接字库 5 int main() 6 { 7 WSADATA data;//定义WSADATA结构体 8 WORD w=MAKEWORD(2,0);//定义版本号 9 ::WSAStartup(w,&data);//初始化套接字库 10 SOCKET s; 11 char sztext[16]={0}; 12 s=::socket(AF_INET,SOCK_STREAM,0);//创建TCP套接字 13 sockaddr_in addr; 14 addr.sin_family=AF_INET;//初始化地质结构 15 addr.sin_port=htons(75); 16 addr.sin_addr.S_un.S_addr=inet_addr("10.203.117.150"); 17 printf("Clienct already start\r\n"); 18 ::connect(s,(sockaddr*)&addr,sizeof(addr)); 19 ::recv(s,sztext,sizeof(sztext),0); 20 printf("%s\r\n",sztext); 21 ::closesocket(s); 22 ::WSACleanup();//释放套接字库 23 if(getchar()) 24 { 25 return 0; 26 } 27 else 28 { 29 ::Sleep(100); 30 } 31 }