Re: Asynchronous connection to socket always appears to succeed?
Pontus Rodling <[email protected]>
| Newsgroups | gmane.comp.lang.pike.user |
|---|---|
| Message-ID | <[email protected]> |
Hi Chris,
I can't say I've seen it done that way before but, here are two examples
of what I usually do using connect() or async_connect():
---
Stdio.File sock = Stdio.File();
int main() {
int r = sock->connect("127.0.0.1", 23);
if (!r) {
werror("error: %s\n", strerror(sock->errno()));
return 1;
}
sock->set_nonblocking(sockread, sockwrite, sockclose);
// ...
return -1;
}
---
Or with async_connect() to prevent blocking main() while connecting:
---
Stdio.File sock = Stdio.File();
int main() {
sock->async_connect("127.0.0.1", 23, sockconnect);
return -1;
}
void sockconnect(int ok) {
if (ok) {
write("Connected!\n");
sock->set_nonblocking(sockread, sockwrite, sockclose);
// ...
}
else {
werror("Connection failed!\n");
exit(1);
}
}
---
Best regards,
Pontus Rodling
On 07/22/2015 12:47 PM, Chris Angelico wrote:
> Pike 8.1 on Linux.
>
> The following script ought to come through to connfailed() in the
> event that there is no TELNET server on localhost. Instead, it comes
> through to connected(), then afterward to sockclosed(). Am I doing
> something stupidly wrong with asynchronous connections here?
>
> object sock;
>
> void sockread(mixed dummy,string data) {write("Data received: %O\n",data);}
> void sockwrite() {write("Socket available for writing\n");}
> void sockclosed() {write("Socket closed, terminating.\n"); exit(0);}
>
> void connected()
> {
> write("Connection appears successful [errno is %d]\n",sock->errno());
> sock->set_nonblocking(sockread,sockwrite,sockclosed);
> }
>
> void connfailed()
> {
> write("Error connecting: %s [%d]\n",strerror(sock->errno()),sock->errno());
> sock->close();
> sockclosed();
> }
>
> int main()
> {
> sock=Stdio.File(); sock->open_socket();
> sock->set_nonblocking(0,connected,connfailed);
> sock->connect("127.0.0.1",23);
> return -1;
> }
>
> ChrisA
>