Thread Wie mit blockierenden Funktionen umgehen?: Socket recv (8 answers)
Opened by HuberDe at 2006-12-18 12:07

styx-cc
 2006-12-21 18:42
#72600 #72600
User since
2006-05-20
533 Artikel
BenutzerIn

user image
ja, sid_burn mit select gehts. Ich schreibe auch gerade einen Clienten und habe habe mich mit der Thematik befasst, mit IO::Select (auch mit select()) kannst du ein Timeoute setzen, nach dem die schleife ein mal "durchrutscht", ich poste mal den Code den ich da zusammen gebaut habe, ist allerdings noch absolute Testphase :)
Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
my $SOCK;
sub main_connection {
my $text = shift;#prompt-msg
sleep(30) unless $FST;#provide serverflooding
$FST = 0;
print "$text\n";
$SOCK = shake_hands();
login();
#use select to have a non-blocking socket
my $sock = new IO::Select( $SOCK );
main_loop($sock);
} #sub main_connection

sub main_loop {
my $sock = shift;
my $died = 0;#check flag
while (1) {
#get data from socket, if there some
while ((my @ready = $sock->can_read(240))) {
for my $fh (@ready) {#checkout readable fhs
if($fh == $SOCK) {
my $input;
unless(sysread($SOCK,$input,2048)) { $died = 1 };
last if $died;
if($input) {
ping_check();
#in some cases we've more than one cmd in a line
#so we've to split them by \n, cause server seperates by \n
my @cmds = split /\n/, $input;
for my $line (@cmds) {
open_log() unless check_log("logs/$logfile");
start($line);
}
} else {
print "unknow socketerror...\n";#syswrite returns 1, but we haven't some input?
}
last;
}
}
last if $died;
}
last if $died;
ping_check() or last;
print "Nichts passiert!\n";
}
$sock = main_connection('Socketerror, trying to reconnect..');
main_loop($sock);
} #main_loop()

sub shake_hands {
my $host = 'www.example.com';
my $port = '0000';
#open socket to chatserver
my $socket = IO::Socket::INET->new(
PeerAddr => $host,
PeerPort => $port,
proto => 'tcp',
type => 'SOCK_STREAM',
Timeout => 20);
main_connection("No Network! Relogin..") unless $socket;
return $socket;
} #sub shake_hands

Vielleicht hilft das ja weiter,
wenn auf dem Socket 240 Sekunden lang ncihts passiert, gibt er einmal "Nichts passiert!" aus.
MfG

Edit: das laeuft auf Windows und unter Linux\n\n

<!--EDIT|styx-cc|1166719531-->
Pörl.

View full thread Wie mit blockierenden Funktionen umgehen?: Socket recv