关于端口释放的问题,高分求教~~
socket编程中,把一个socket与一个端口绑定,发送完数据后,再把该socket关闭,用的是 close语句。但是下次再运行该程序时,提示该端口被占用,每次只能换个端口重新运行,如何解决。
问题点数:0、回复次数:1Top
1 楼masterz(www.fruitfruit.com)回复于 2004-04-02 18:24:58 得分 0
bool ShutdownConnection(SOCKET sd)
{
// Disallow any further data sends. This will tell the other side
// that we want to go away now. If we skip this step, we don't
// shut the connection down nicely.
if (shutdown(sd, SD_SEND) == SOCKET_ERROR) {
return false;
}
const int kBufferSize = 1024;
// Receive any extra data still sitting on the socket. After all
// data is received, this call will block until the remote host
// acknowledges the TCP control packet sent by the shutdown above.
// Then we'll get a 0 back from recv, signalling that the remote
// host has closed its side of the connection.
char acReadBuffer[kBufferSize];
int maxtry = 100;
while (maxtry>0)
{
maxtry--;
int nNewBytes = recv(sd, acReadBuffer, kBufferSize, 0);
if (nNewBytes == SOCKET_ERROR)
{
return false;
}
else if (nNewBytes > 0)
{
/*
char msgbuf[1024];
wsprintf(msgbuf,"%s:%d FYI, received %d unexpected bytes during shutdown.",
__FILE__,__LINE__,nNewBytes);
OutputDebugString(msgbuf);
*/
//break;
}
else
{
// Okay, we're done!
break;
}
}
// Close the socket.
if (closesocket(sd) == SOCKET_ERROR) {
return false;
}
return true;
}Top




