使用SOCKET API写的客户端与服务端测试程序(C语言)

 服务端程序:

int main(int argc, char* argv[]) { int sock,length; struct sockaddr_in server; struct sockaddr tcpaddr; int msgsock; char buf[1024]; int rval,len; //initialization socket WSADATA wsaData; WSAStartup(MAKEWORD(2,0),&wsaData); //create new socket sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) { perror("opening stream socket"); printf("sock=%d/n",sock); getch(); exit(1); } //bind the socket server.sin_family=AF_INET; server.sin_addr.S_un.S_addr=inet_addr("172.17.26.69");//此处请设定服务器自己的IP,如果是在本机测试请设置为127.0.0.1 server.sin_port=htons(5000);//INADDR_ANY; if(bind(sock,(struct sockaddr *)&server,sizeof(server))<0) { perror("binding stream socket"); printf("lasterror: %d/n",WSAGetLastError()); getch(); exit(1); } length=sizeof(server); if(getsockname(sock,(struct sockaddr *)&server,&length)<0) { perror("getting socket name"); getch(); exit(1); } printf("socket port # %d/n",ntohs(server.sin_port)); //listen socket listen(sock,5); len=sizeof(struct sockaddr); do { printf("gogo"); msgsock=accept(sock,(struct sockaddr *)&tcpaddr,(int *)&len); printf("msgsock=%d/n",msgsock); if(msgsock==-1) perror("accept"); else do { memset(buf,0,sizeof(buf)); if((rval=recv(msgsock,buf,1024,0))<0) perror("reading stream message"); if(rval==0) printf("ending connection /n"); else printf("---->%s/n",buf); }while(rval!=0); closesocket(msgsock); }while(TRUE); getch(); return 0; }

客户段程序:

int main(int argc, char* argv[]) { int iResult; SOCKET MySocket=INVALID_SOCKET; struct sockaddr_in MyAddr; struct hostent *hp; unsigned long nClient; WSADATA wsaData; char COMPUTERNAME[255]; char *DATA="it's hrre."; //initialization socket iResult = WSAStartup(MAKEWORD(2,2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d/n", iResult); return 1; } if((MySocket=socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET) { printf("socket error, lasterror: %d/n",WSAGetLastError()); return 1; } //connect socket memset((void*)&MyAddr,0,sizeof(MyAddr)); MyAddr.sin_family=AF_INET; MyAddr.sin_port=htons(5000); MyAddr.sin_addr.S_un.S_addr=inet_addr("172.17.161.46");//此处请设定服务器IP if(connect(MySocket,(struct sockaddr *)&MyAddr,sizeof(struct sockaddr))==SOCKET_ERROR) { printf("connect error ,lasterror :%d/n",WSAGetLastError()); getch(); exit(1); } //send data to server if(send(MySocket,DATA,10,0)<0) perror("sending on stream socket"); closesocket(MySocket); //getch(); return 0; }

你可能感兴趣的:(c,socket,api,Stream,测试,语言)