服务端:#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#include
SOCKET sckt;
struct sockaddr_in scktinf;
//SOCKET clnt;
struct clntStrc
{
int nmr;
char nm[0x20];
SOCKET sckt;
}clntAr[100];
int flg;
int rmSnd();
int rmRcv(struct clntStrc *);
int rmLstn();
char *IMPSTNMR="_IMPSTNMR@%d";
int c;
int rmRcv(struct clntStrc *clnt)
{
char strg[0x1000],strg2[0x1000];
int f;
//pthread_t thrSnd;
//pthread_create(&thrRcv,NULL,rmSnd,sckt);
int t;
int n;
while (1)
{
f=recv(clnt->sckt,strg,0x100,0);
//printf("%s\n",strg);
if (f<0) break;
switch(strg[0])
{
case '&':
{
t=strtol(strg+1,NULL,10);
sprintf(strg2,"*%d%s\n",clnt->nmr,strchr(strg,'@'));
send(clntAr[t].sckt,strg2,strlen(strg),0);
break;
}
default:
{
printf("CLIENT#%d:%s\n",clnt->nmr,strg);
strcpy(strg,"");
}
}
//clnt=accept(sckt,NULL,NULL);
//flg=1;
/*
f=-1;
if (recv(clnt->sckt,strg,0x100,0)>=0)
{
printf("CLIENT#%d:%s\n",clnt->nmr,strg);
strcpy(strg,"");
}
*/
}
}
int rmSnd()
{
char strg[0x1000],strg2[0x1000];
int n;
while (1)
{
gets(strg);
switch (strg[0])
{
case '&':
{
n=strtol(strg+1,NULL,10);
strcpy(strg2,strchr(strg,'@'));
//printf("ECHO:%s\n",strg2);
send(clntAr[n].sckt,strg2,strlen(strg2),0);
}
case '_':
{
}
}
//sprintf(strg,"%d@%s",n,strg2);
//if (send(sckt,strg,strlen(strg),0)>=0)
//{
//flg=1;
//}
}
}
int rmLstn()
{
SOCKET clnt,tclnt;
c=0;
char strg[0x1000];
char tNmr[0x10];
int f;
pthread_t thrRcv,thrSnd;
pthread_create(&thrSnd,NULL,rmSnd,NULL);
SOCKET *tClnt;
int tLen=sizeof(scktinf);
char msgNmr[0x1000];
while (1)
{
c+=1;
clntAr[c].sckt=accept(sckt,&scktinf,&tLen);
clntAr[c].nmr=c;
//memcpy()
//tClnt=malloc(sizeof(SOCKET));
//memcpy(tClnt,&clnt,sizeof(SOCKET));
pthread_create(&thrRcv,NULL,rmRcv,clntAr+c);
sprintf(msgNmr,IMPSTNMR,c);
send(clntAr[c].sckt,msgNmr,strlen(msgNmr),0);
/*
if (clnt>=0)
{
//printf("LEGATO#%d\n",clnt&0xFF);
//printf("LEGATO\n");
//c++;
//itoa(c,tNmr,10);
//while (send(clnt,tNmr,strlen(tNmr),0)<0);
//f=recv(clnt,strg,0x1000,0);
//pthread_create(&thrSnd,NULL,rmSnd,clnt);
}
*/
}
}
int main()
{
WSADATA WSD;
WSAStartup(MAKEWORD(2,2),&WSD);
char adrs[0x20];
scanf("%s",adrs);
while (adrs[strlen(adrs)-1]=='\r' || adrs[strlen(adrs)-1]=='\n')
{
adrs[strlen(adrs)-1]='\0';
}
scktinf.sin_addr.s_addr=inet_addr(adrs);
scktinf.sin_port=htons(2070);
scktinf.sin_family=2;
sckt=socket(2,1,0);
bind(sckt,&scktinf,sizeof(scktinf));
listen(sckt,10);
flg=0;
pthread_t thrdLstn;
pthread_create(&thrdLstn,NULL,rmLstn,NULL);
pthread_join(thrdLstn,NULL);
//pthread_t thrdRcv,thrdSnd;
//pthread_create(&thrdRcv,NULL,rmRcv,NULL);
//pthread_create(&thrdSnd,NULL,rmSnd,NULL);
//pthread_join(thrdRcv,NULL);
//pthread_join(thrdSnd,NULL);
}
原文:http://blog.51cto.com/13715730/2106627