永发信息网

求VC高手解释一下语句

答案:1  悬赏:20  手机版
解决时间 2021-03-24 05:32
  • 提问者网友:战魂
  • 2021-03-23 10:12
求VC高手解释一下语句
最佳答案
  • 五星知识达人网友:轻熟杀无赦
  • 2021-03-23 11:10
这没啥说的啊! 就调用几个sock函数
#include
DWORD WINAPI ClientThread(LPVOID lpParam);
int main()
{
WORD wVersionRequested;
DWORD ret;
WSADATA wsaData;
BOOL val;
SOCKADDR_IN saddr;
SOCKADDR_IN scaddr;
int err;
SOCKET s;
SOCKET sc;
int caddsize;
HANDLE mt;
DWORD tid;
wVersionRequested = MAKEWORd( 2, 2 ); //取版本号
err = WSAStartup( wVersionRequested, &wsaData );//安装sock
if ( err != 0 )

{
printf("error!WSAStartup failed!\n");
return -1;
}
saddr.sin_family = AF_INET;

saddr.sin_addr.s_addr = inet_addr("192.168.0.60"); //IP地址
saddr.sin_port = htons(23); //端口
if((s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==SOCKET_ERROR) //创建一个套接字
{
printf("error!socket failed!\n");

return -1;
}
val = TRUE;
//SO_REUSEADDR选项就是可以实现端口重绑定的
if(setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val))!=0)
{
printf("error!setsockopt failed!\n");
return -1;
}

//绑定
if(bind(s,(SOCKADDR *)&saddr,sizeof(saddr))==SOCKET_ERROR)
{
ret=GetLastError();
printf("error!bind failed!\n");

return -1;
}
listen(s,2); //监听
while(1)
{
caddsize = sizeof(scaddr); //接受连接请求
sc = accept(s,(struct sockaddr *)&scaddr,&caddsize);
if(sc!=INVALID_SOCKET)
{
//创建一个线程处理连接请求
mt = CreateThread(NULL,0,ClientThread,(LPVOID)sc,0,&tid);
if(mt==NULL)
{
printf("Thread Creat Failed!\n");
break;
}

}
CloseHandle(mt);
}
closesocket(s); //关闭sock
WSACleanup(); //卸装sock
return 0;
}

DWORD WINAPI ClientThread(LPVOID lpParam)
{
SOCKET ss = (SOCKET)lpParam;
SOCKET sc;
unsigned char buf[4096];
SOCKADDR_IN saddr;
long num;
DWORD val;
DWORD ret;

saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
saddr.sin_port = htons(23);
if((sc=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==SOCKET_ERROR)
{
printf("error!socket failed!\n");
return -1;
}

val = 100;
if(setsockopt(sc,SOL_SOCKET,SO_RCVTIMEO,(char *)&val,sizeof(val))!=0)
{
ret = GetLastError();
return -1;
}
if(setsockopt(ss,SOL_SOCKET,SO_RCVTIMEO,(char *)&val,sizeof(val))!=0)
{
ret = GetLastError();
return -1;
}
//建立连接
if(connect(sc,(SOCKADDR *)&saddr,sizeof(saddr))!=0)
{
printf("error!socket connect failed!\n");
closesocket(sc);
closesocket(ss);
return -1;
}

while(1)
{

num = recv(ss,buf,4096,0); //接收信息
if(num>0)
send(sc,buf,num,0); //发送信息
else if(num==0)
break;
num = recv(sc,buf,4096,0);
if(num>0)
send(ss,buf,num,0);
else if(num==0)

break;
}
closesocket(ss);
closesocket(sc);
return 0 ;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯