Skip to content

Instantly share code, notes, and snippets.

@thwarted
Created September 30, 2009 07:35
Show Gist options
  • Save thwarted/197900 to your computer and use it in GitHub Desktop.
Save thwarted/197900 to your computer and use it in GitHub Desktop.
quick comparison of using an iterator to accept network connections
#!/usr/bin/perl
use strict;
use warnings;
package ReceiveConnection;
use IO::Socket::INET;
sub TIEARRAY {
my $class = shift;
my $listener = IO::Socket::INET->new(@_);
return bless [$listener], $class;
}
sub SHIFT {
my $self = shift;
my $sock = $self->[0]->accept();
my($peerport, $peeraddr) = sockaddr_in($sock->peername);
return [$sock, sprintf('%s:%d', inet_ntoa($peeraddr), $peerport)];
}
package main;
my @listener = ();
tie @listener, 'ReceiveConnection', LocalAddr=>'127.0.0.1', LocalPort=>9000, Proto=>'tcp', Listen=>5;
while (my $newconn = shift @listener) {
my($c, $a) = @$newconn;
print "Got connection from $a\n";
my $msg = "Hello World\n";
$c->send($msg);
$c->shutdown(2);
}
#!/usr/bin/php
<?php
class ReceiveConnection implements Iterator {
private $addr;
private $port;
private $sock;
private $count;
private $cur;
public function __construct($addr, $port) {
$this->addr = $addr;
$this->port = $port;
}
public function current() {
if (!isset($this->cur)) $this->next();
return $this->cur;
}
public function rewind() {
$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($this->sock, $this->addr, $this->port);
socket_listen($this->sock);
}
public function key() {
return $this->count;
}
public function next() {
$this->count++;
$cur = socket_accept($this->sock);
$peeraddr = '';
$peerport = '';
socket_getpeername($cur, $peeraddr, $peerport);
$this->cur = array($cur, sprintf('%s:%d', $peeraddr, $peerport));
return $this->cur;
}
public function valid() {
return true;
}
}
foreach (new ReceiveConnection("127.0.0.1", 9000) as $c) {
list($c, $a) = $c;
print "Got connection from $a\n";
$msg = "Hello World\n";
socket_send($c, $msg, strlen($msg), 0);
socket_close($c);
}
#!/usr/bin/python
import socket
def ReceiveConnection(port, addr='127.0.0.1'):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((addr, port))
server.listen(5)
while True:
(c, peerinfo) = server.accept()
peerinfo = "%s:%d" % peerinfo
yield (c, peerinfo)
for c in ReceiveConnection(port=9000):
c, a = c
print("Got connection from %s" % (a))
msg = "Hello World\n"
c.send(msg)
c.shutdown(socket.SHUT_RDWR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment