客户端:
1 #include<stdio.h> 2 #include<winsock2.h> 3 #pragma comment (lib,"ws2_32") 4 int main(int argc,char *argv[]) 5 { 6 7 WSADATA wsaData; 8 WSAStartup(MAKEWORD(2,2),&wsaData); 9 10 SOCKET s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);//申请套接字 11 12 sockaddr_in sockaddr; //申请地址结构,并补充相关信息 13 sockaddr.sin_family=PF_INET; 14 sockaddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); //该IP用于本地测试用的,运行时请删除注释 15 sockaddr.sin_port=htons(827); //随机选择了个端口 16 17 connect(s,(SOCKADDR*)&sockaddr,sizeof(SOCKADDR));//连接到服务器 18 while(1){ 19 char Buff[MAXBYTE]={0}; 20 char Cmd[MAXBYTE]={0}; 21 recv(s,Cmd,MAXBYTE,0); 22 printf("%s",Buff); 23 scanf("%s",Cmd); 24 send(s,Cmd,MAXBYTE,0); 25 if(!strcmp(Cmd,"exit")){ 26 printf("Login out!\r\n"); 27 break; 28 } 29 memset(Buff,0,MAXBYTE); 30 recv(s,Buff,MAXBYTE,0); 31 printf("%s\r\n",Buff); 32 33 } 34 35 closesocket(s); 36 getchar(); 37 WSACleanup(); 38 return 0; 39 40 }
服务器端:
1 #include<winsock2.h> 2 #include <mmsystem.h> 3 #pragma comment (lib,"ws2_32") 4 #pragma comment (lib,"Winmm") 5 6 BOOL Dispatch(SOCKET sock,char *Cmd) 7 { 8 BOOL bRet=FALSE; 9 if(!strcmp(Cmd,"help")){ 10 send(sock,"client:hehe\r\n",strlen("hehe\r\n")+sizeof(char),0); 11 bRet=TRUE; 12 }else if(!strcmp(Cmd,"open")){ 13 mciSendString("set cdaudio door open",NULL,NULL,NULL); 14 send(sock,"client:open\r\n",strlen("client:open\r\n")+sizeof(char),0); 15 bRet=TRUE; 16 } 17 return bRet; 18 } 19 int main(int argc,char *argv[]) 20 { 21 WSADATA wsaData; 22 WSAStartup(MAKEWORD(2,2),&wsaData); 23 24 SOCKET s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); 25 26 sockaddr_in sockaddr; 27 sockaddr.sin_family=PF_INET; 28 sockaddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY); 29 sockaddr.sin_port=htons(827); 30 31 bind(s,(SOCKADDR*)&sockaddr,sizeof(SOCKADDR));//套接字与地址结构进行绑定 32 listen(s,1);//监听连接的最大数量 33 SOCKADDR clientAddr; 34 int nSize=sizeof(SOCKADDR); 35 SOCKET clientSock;//接受客户端的连接的套接字 36 clientSock=accept(s,(SOCKADDR*)&clientAddr,&nSize);//阻塞,等待用户连接 37 38 //end(clientSock,"hello client \r\n",strlen("hello client \r\n")+sizeof(char),NULL); 39 40 while(1){ 41 send(clientSock,"shell>",strlen("shell>")+sizeof(char),0); 42 char buff[MAXBYTE]={0}; 43 recv(clientSock,buff,MAXBYTE,0); 44 if(!strcmp(buff,"exit")){break;} 45 BOOL bRet=Dispatch(clientSock,buff); 46 if(bRet==FALSE) 47 { 48 send(clientSock,"Command Unsuccessfully!",strlen("Command Unsuccessfully!")+sizeof(char),0); 49 } 50 } 51 52 53 closesocket(clientSock); 54 closesocket(s); 55 56 WSACleanup(); 57 return 0; 58 }
时间: 2024-10-21 13:42:38