PDA

View Full Version : How to recognize the server socket is currently available?



compext
12-13-2006, 10:14 AM
I have 2 simple codes on Linux, cli.c and svr.c



// -------------------cli.c-----------------------------
int main()
{
int sock = socket(PF_INET, SOCK_STREAM, 0), csock;
SOCKADDR_IN sin, csin;
int csinsize = sizeof(csin), read;
char buf[4096];

Logi(sock);

sin.sin_family = PF_INET;
sin.sin_port = htons(3000);
sin.sin_addr.s_addr = inet_addr("192.168.10.10");

while (TRUE)
{
// csock = accept(sock, (PSOCKADDR) &csin, &csinsize);
Logi(connect(sock, (PSOCKADDR) &sin, sizeof(sin)));
while ((read = recv(sock, buf, 4096, 0)) > 0)
{
Log("read:");
Logi(read);
}
Log("Connect closed.");
}

return 0;
}

//-----------------svr.c--------------------------
int main()
{
int sock = socket(PF_INET, SOCK_STREAM, 0), csock;
SOCKADDR_IN sin, csin;
int csinsize = sizeof(csin), read;
char buf[4096];

#ifdef DAEMON
gLogfp = fopen("arpl", "w");
daemon(0, 0);
#endif

Logi(sock);

sin.sin_family = PF_INET;
sin.sin_port = htons(3000);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&sin.sin_zero, 8);
Logi(bind(sock, (PSOCKADDR) &sin, sizeof(sin)));

Logi(listen(sock, 10));

while (TRUE)
{
Logi(csock = accept(sock, (PSOCKADDR) &csin, &csinsize));
while ((read = recv(csock, buf, 4096, 0) > 0))
{
Log("read");
Logi(read);
}
Log("Connect closed.");
}

return 0;
}

Both client and server is run in daemon, and the socket is really established between each other. However, when I reboot the server(192.168.10.10), client could not feel this, it is still pending at the function recv, the socket is still established seen from netstat. :( Can anyone give me a hint? Thanks.