tcp socket 辅导讲解、讲解socket 程序代码
- 首页 >> Webclass server//创ä¡ä建¡§服¤t务?器¡Â的Ì?类¤¨¤
{
public:
server()//服¤t务?器¡Â类¤¨¤构1造¨¬函¡¥数ºy
{
surplus_cpu=1;//初?始º?化¡¥剩º¡ê余®¨¤CPU为a1
surplus_memory=1;//初?始º?化¡¥剩º¡ê余®¨¤内¨²存ä?为a1
}
bool is_full()//判D断?服¤t务?器¡Â是º?否¤?已°?满¨²
{
if(surplus_memory<=0.0005||surplus_cpu<=0.00005)//取¨?值¦Ì为a两¢?属º?性?最Á?小?值¦Ì
return 1;
else
return 0;
}
bool overstep(double cpu,double memory)//判D断?是º?否¤?能¨¹将?进?程¨¬放¤?入¨?服¤t务?器¡Â中D
{
if(surplus_cpu-cpu>=0&&surplus_memory-memory>=0)
return 1;
else
return 0;
}
double is_fit(double cpu,double memory)//判D断?最Á?合?适º¨º服¤t务?器¡Â的Ì?进?程¨¬
{
e_percent=surplus_cpu*cpu+surplus_memory*memory;//计?算?进?程¨¬向¨°量¢?的Ì?内¨²积y
return e_percent;//向¨°量¢?内¨²积y
}
void lead_in(double cpu,double memory)//将?进?程¨¬放¤?入¨?服¤t务?器¡Â中D
{
surplus_cpu=cpu;
surplus_memory=memory;//剩º¡ê余®¨¤memory减?少¦¨´
};
~server()
{
quantity++;//一°?次ä?析?构1代䨲表À¨ª用®?完ª¨º一°?个?服¤t务?器¡Â,ê?建¡§立¢¡é在¨²动¡¥态¬?分¤?配?的Ì?基¨´础ä?上¦?
}
static int quantity;//服¤t务?器¡Â数ºy量¢?
private:
double surplus_cpu;
double surplus_memory;
double e_percent;//向¨°量¢?内¨²积y
};
【源文件】
#include<iostream>
#include"server.h"
#include<fstream>
int server::quantity=0;
using namespace std;
int main()
{
double data[1000][3];//创ä¡ä建¡§容¨Y纳¨¦进?程¨¬的Ì?二t维?数ºy组Á¨¦
ifstream infile;
infile.open("1000个?进?程¨¬CPU和¨ª内¨²存ä?占?用®?量¢?.Txt");//打䨰开a数ºy据Y文?件t
if(!infile.is_open())
{
cout<<"文?件t打䨰开a失º¡ì败㨹"<<endl;//检¨¬测a文?件t是º?否¤?打䨰开a
return 0;
}
for(int i=0;i<1000;i++)
{
for (int j=0;j<3;j++)
infile>>data[i][j];
};
infile.close();
server*x=new server();//创ä¡ä建¡§一°?个?服¤t务?器¡Â
for(int k=0;k<1000;k++)//从䨮第̨²一°?个?进?程¨¬开a始º?遍À¨¦历¤¨²
{
if(x->is_full())//检¨¬测a服¤t务?器¡Â是º?否¤?已°?满¨²
{
delete x;
server*x=new server();
}
double max_m=0;
int max_l=0;
for(int l=k;l<1000;l++)//开a始º?寻¡ã找¨°内¨²积y最Á?大䨮的Ì?进?程¨¬
{
if(x->overstep(data[l][1],data[l][2]))//判D断?进?程¨¬能¨¹否¤?放¤?入¨?进?程¨¬内¨²
{
double m=x->is_fit(data[l][1],data[l][2]);//得Ì?出?内¨²积y
if(m>max_m)//比À¨¨较?大䨮小?
{
max_m=m;
max_l=l;
}
}
if(max_l!=-1)//有®D进?程¨¬能¨¹够?放¤?到Ì?服¤t务?期¨²内¨²
{
x->lead_in(data[max_l][l],data[max_l][2]);
cout<<data[max_l][0]<<"";//被À?注Á¡é释º¨ª掉Ì?的Ì?调Ì¡Â试º?信?息¡é
for(int a=0;a<3;a++)//将?使º1用®?过y的Ì?进?程¨¬放¤?到Ì?前¡ã面?去¨£¤
data[max_l][a]=data[k][a];
}
else//没?有®D进?程¨¬能¨¹够?放¤?到Ì?服¤t务?器¡Â内¨²
{
delete x;//下?一°?个?服¤t务?器¡Â
cout<<endl;//被À?注Á¡é释º¨ª掉Ì?的Ì?调Ì¡Â试º?信?息¡é
server*x=new server();
k--;//重?新?遍À¨¦历¤¨²上¦?一°?个?进?程¨¬
}
}
delete x;
cout<<endl;//被À?注Á¡é释º¨ª掉Ì?的Ì?调Ì¡Â试º?信?息¡é
cout<<"使º1用®?服¤t务?器¡Â数ºy量¢?的Ì?一°?个?较?小?值¦Ì为a:"<<server::quantity<<"个?"<<endl;
return 0;
}