客户端
//client.cpp : Defines the entry point for the console application.
//
#include<stdlib.h>
#include "stdafx.h"
#define BUF_SIZE 1024
#include<winsock2.h>
//void error_handling(char *message);
int main(int argc, char *argv[]){
//Windows Socket DLL初始化
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0){
printf("WSAStartup() error!");
}
//地址信息
SOCKADDR_IN servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servAddr.sin_port = htons(2000);
int i;
for(i=1;i<=30000;i++)
{
SOCKET hServSock;
hServSock = socket(AF_INET, SOCK_STREAM, 0);
if(hServSock == INVALID_SOCKET){
printf("socket() error");
}
//循环连接服务器
if(connect(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR)
printf("服务器崩溃\n");
else
printf("第%d次连接,\n",i);
}
//关闭套接字
//closesocket(hServSock);
WSACleanup();
return 0;
}
/*
void error_handling(char *message){
fputs(message, stderr);
fputc('\n',stderr);
exit(0);
}*/
服务器端
// 服务器端.cpp : Defines the entry point for the console application.
//
// 实验二.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<winsock2.h>
int main(int argc, char* argv[])
{
char recvbuf[100];
int recvbuflen=100;
sockaddr_in addrClient;
int addrClientlen=sizeof(sockaddr_in);
//验证参数的合法性;
if(argc!=3){
printf("usage:%s sever-name\n",argv[0]);
}
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
if(iResult!=0){
printf("初始化不成功 error %d\n",iResult);
return 1;
}
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in hints;
hints.sin_family = AF_INET;
hints.sin_port = htons(2000);
hints.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (s == INVALID_SOCKET)
{ printf("初始化不成功 error \n");
WSACleanup();
}
int result=bind(s, (struct sockaddr*)&hints, sizeof(hints));
if(result==-1)
{
printf("Failed to bind socket. Error code: %d\n", WSAGetLastError());
printf("Failed to bind socket\n");
WSACleanup();
return 1;
}
listen(s,105);
fd_set fdRead,fdSocket;
FD_ZERO (&fdSocket);
FD_SET(s,&fdSocket);
int num=0;
while(1){
fdRead=fdSocket;
iResult=select(0,&fdRead,NULL,NULL,NULL);
if(iResult>0){
for(int i=0;i<(int)fdSocket.fd_count;i++){
if(FD_ISSET(fdSocket.fd_array[i],&fdRead)){
if (fdSocket.fd_array[i] == s){
SOCKET AcceptSocket=accept(s,(struct sockaddr *)&addrClient,&addrClientlen);
if(AcceptSocket==INVALID_SOCKET){
printf("accept failed\n");
closesocket(s);
WSACleanup();
return 1;
}
num++;
FD_SET(AcceptSocket,&fdSocket);
printf("接收到新的连接:%s,%d\n",inet_ntoa(addrClient.sin_addr),ntohs(addrClient.sin_port));
printf("第%d次连接\n",num);
}
}
}
}
else{
printf("select failed ,错误码为:%d\n",WSAGetLastError());
break;
}
}
closesocket(s);
WSACleanup();
return 0;
}