Winsocket 多线程TCP编程 无法关闭端口
连接能正常,但是但连接断开后再次连接时,调式工具提示“本地端口还没有完全释放”,关闭socket不就是调用closesocket()就可以了吗??#include <stdafx.h>#include "Sever.h"
#include <stdio.h>
struct ConnetInfo
{
SOCKET ConnetedSocket;
SOCKADDR_IN addrClient;
};
SOCKET SeverListenSocket;
SOCKET ConnetSocket;
UINT16 test=123;
struct ConnetInfo ConnetSocketInfo;
DWORD WINAPI SeverListenThread(LPVOID lpParamter)
{
printf("进入监听线程\r\n");
//加载套接字库
WORD wVersionRequested;
WSADATA wsaData;
int err;
int recv_len;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested,&wsaData);
if(err != 0) return 0;
//判断是不是请求的版本
if(LOBYTE(wsaData.wVersion) !=1 || HIBYTE(wsaData.wVersion) !=1)
{
WSACleanup();
return 0;
}
//创建用于监听的套接字
SeverListenSocket=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//任意可用的IP地址
addrSrv.sin_family=AF_INET;//IPv4
addrSrv.sin_port=htons(6000);//监听的端口号
//bind
bind(SeverListenSocket,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
while (1)
{
printf("等待客户端连接\n");
listen(SeverListenSocket,5);
SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
//接受一个连接
ConnetSocketInfo.ConnetedSocket=accept(SeverListenSocket,(SOCKADDR*)&ConnetSocketInfo.addrClient,&len);
CreateThread(NULL,0,SeverThread,&ConnetSocketInfo,0,NULL);
Sleep(100);
}
return 0;
}
DWORD WINAPI SeverThread(LPVOID lpParamter)
{
struct ConnetInfo ConnetSocketInfo;
UINT8 RecvBuf;
int len=0;
printf("进入\n");
ConnetSocketInfo=*((struct ConnetInfo*)lpParamter);
//打印IP、端口信息
printf("IP:%d.%d.%d.%d\n",
ConnetSocketInfo.addrClient.sin_addr.S_un.S_un_b.s_b1,
ConnetSocketInfo.addrClient.sin_addr.S_un.S_un_b.s_b2,
ConnetSocketInfo.addrClient.sin_addr.S_un.S_un_b.s_b3,
ConnetSocketInfo.addrClient.sin_addr.S_un.S_un_b.s_b4);
printf("端口:%d\n",ntohs(ConnetSocketInfo.addrClient.sin_port));
send(ConnetSocketInfo.ConnetedSocket,"123456",6,0);
while (1)
{
len=recv(ConnetSocketInfo.ConnetedSocket,(char *)RecvBuf,sizeof(RecvBuf),0);
if(len<=0)
{
printf("产生错误或客户端关闭\n");
break;
}
//Sleep(200);
}
closesocket(ConnetSocketInfo.ConnetedSocket);
printf("结束本线程\n");
return 0;
} 发现过了一段时间后有可以连接了,有点奇怪。
可能是不够了解WinSocket原理吧 在bind或者listen之前,设置socket的reuse属性为true即可
页:
[1]