gpt4 book ai didi

c - 端口正在监听但 "No connection could be made because the target machine actively refused it "

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:55 25 4
gpt4 key购买 nike

我有一个服务器/客户端程序。该代码仅在几分钟前有效。跑了几次突然报错10061,我用“netstat -a -b”查看服务器端口是否被占用。但我得到这个似乎没问题:

[System]
TCP 0.0.0.0:6666 Listening

客户端代码:

SOCKET sendrecv;
sendrecv = InitClientSocket(serverIP, 6666);

附言。 ping serverIP 也可以。防火墙也关了。

SOCKET InitClientSocket(char *pHost, int iPort){
struct sockaddr_in saClient;
struct hostent *pHostinfo;
SOCKET sock;

WORD version;
WSADATA WSAData;
version=MAKEWORD(1,1);
WSAStartup(version, &WSAData);

sock=socket(AF_INET,SOCK_STREAM,0);
if (sock ==SOCKET_ERROR){
closesocket(sock);
return 0;
}

pHostinfo=gethostbyname(pHost);
if (pHostinfo==NULL){
closesocket(sock);
return 0;
}

saClient.sin_family=AF_INET;
saClient.sin_addr=*((struct in_addr *)pHostinfo->h_addr);
saClient.sin_port=htons(iPort);

int nConnect=0;
nConnect=connect(sock,(struct sockaddr *)&saClient, sizeof(saClient));
if(nConnect == SOCKET_ERROR) //Here comes the error 10061
{
int err = WSAGetLastError();
closesocket(sock);
return 0;
}

return sock;
}

新编辑 - 这是服务器代码的一部分:

SOCKET sock, sendrecv;
struct sockaddr_in sock_addr,sendrecv_addr;
WSADATA data;

WSAStartup( MAKEWORD(2,0), &data);
sock = WSASocket (AF_INET, SOCK_STREAM, 0, 0, 0, 0);

int nREUSEADDR = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(const char*)&nREUSEADDR,sizeof(int));

sock_addr.sin_family=PF_INET;
sock_addr.sin_port=htons(6666);
sock_addr.sin_addr.s_addr=INADDR_ANY;
bind(sock,(struct sockaddr*)&sock_addr,sizeof(struct sockaddr_in));
listen(sock,1);
int lun = sizeof (struct sockaddr);
sendrecv = accept(sock,(struct sockaddr*)&sendrecv_addr,&lun);

linger m_sLinger;
m_sLinger.l_onoff = 1;
m_sLinger.l_linger = 0;
setsockopt(sendrecv,SOL_SOCKET,SO_LINGER,(const char*)&m_sLinger,sizeof(linger));

最佳答案

Windows 服务器将在其监听积压队列填满后开始拒绝连接。您的服务器接受速度不够快,或者根本不接受。

关于c - 端口正在监听但 "No connection could be made because the target machine actively refused it ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34057215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com