1 package Thrasher
::Socket
;
9 Thrasher::Socket - manage the socket connection to the XMPP server.
13 Thrasher::Socket manages the connection to the XMPP server, and
14 once the connection is successfully established, feeds the socket
22 use Thrasher
::Log
qw(log debug);
28 $self->{host
} = shift;
29 $self->{port
} = shift;
30 $self->{event_loop
} = shift;
36 # Returns the function to feed to the component to write to
41 debug
("OUT: " . join('', @_));
51 my $socket = $self->{socket};
61 if ($self->{connected
}) {
65 my $proto = getprotobyname('tcp');
66 my $iaddr = inet_aton
($self->{host
});
67 my $paddr = sockaddr_in
($self->{port
}, $iaddr);
71 log("Beginning socket connection to $self->{host}:$self->{port}...");
72 socket($socket, PF_INET
, SOCK_STREAM
, $proto)
73 or die "SOCK_CREATE: socket failed to create";
74 connect($socket, $paddr)
75 or die "SOCK_CONNECT: socket failed to connect";
78 binmode($socket, ':encoding(utf8)');
81 fcntl($socket, F_SETFL
, O_NONBLOCK
);
83 $self->{socket} = $socket;
84 $self->{connected
} = 1;
87 sub establish_fd_watch
{
90 $self->{watch_handle
} = $self->{event_loop
}->add_fd_watch
91 ($self->fileno, $Thrasher::EventLoop
::IN
,
92 $self->{read_closure
});
95 sub terminate_fd_watch
{
97 if (!exists($self->{watch_handle
})) {
101 $self->{event_loop
}->remove_fd_watch($self->{watch_handle
});
102 delete($self->{watch_handle
});
107 if (!$self->{connected
}) {
108 die "No socket to get.";
111 return $self->{socket};
117 if (!$self->{connected
}) {
118 die('Trying to read from an unconnected socket.');
122 my $return = sysread($self->{socket}, $value, 65535);
126 # For now restart on all read errors--dunno what state changes we
127 # missed reading. Might eventually be able to reconnect only the
128 # component w/o reconnecting everyone to the public IM network.
129 elsif (! defined($return)) {
131 # Not ready yet. That's OK--return undef and try again later.
135 die("Error reading from component socket: $!");
139 die('EOF when reading from component socket!');
145 $self->{socket}->close;
146 $self->terminate_fd_watch;
147 delete $self->{connected
};
148 delete $self->{socket};
153 return $self->{socket}->fileno;
158 return $self->{socket}->eof;