Beispiel #1
0
 def from_address(cls, addr):
     """Creates a new socket from the given address. If the addr is a tuple (host, port)
     a normal tcp socket is assumed. if addr is a string, a UNIX Domain socket is assumed"""
     if type(addr) == types.StringType:
         return cls(_socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)) 
     else:
         return cls(_socket.socket(_socket.AF_INET, _socket.SOCK_STREAM))
Beispiel #2
0
    def test_subclass(self):
        # Check that the appropriate SSLError subclass is raised
        # (this only tests one of them)
        import _ssl, _socket
        ctx = _ssl._SSLContext(_ssl.PROTOCOL_TLS)
        s = _socket.socket()
        try:
            s.bind(("127.0.0.1", 0))
            s.listen(5)
            c = _socket.socket()
            c.connect(s.getsockname())
            c.setblocking(False)

            c = ctx._wrap_socket(c, False)
            try:
                exc = raises(_ssl.SSLWantReadError, c.do_handshake)
                msg= str(exc.value)
                assert msg.startswith("The operation did not complete (read)")
                # For compatibility
                assert exc.value.errno == _ssl.SSL_ERROR_WANT_READ
            finally:
                try:
                    c.shutdown()
                except _ssl.SSLError:
                    # If the expected exception was raised, the SSLContext
                    # can't be shut down yet
                    pass
        finally:
            s.close()
Beispiel #3
0
    def test_unix_socket_connect(self):
        import _socket, os
        if not hasattr(_socket, 'AF_UNIX'):
            skip('AF_UNIX not supported.')
        oldcwd = os.getcwd()
        os.chdir(self.udir)
        try:
            sockpath = 'app_test_unix_socket_connect'

            serversock = _socket.socket(_socket.AF_UNIX)
            serversock.bind(sockpath)
            serversock.listen(1)

            clientsock = _socket.socket(_socket.AF_UNIX)
            clientsock.connect(sockpath)
            s, addr = serversock.accept()
            assert not addr

            s.send('X')
            data = clientsock.recv(100)
            assert data == 'X'
            clientsock.send('Y')
            data = s.recv(100)
            assert data == 'Y'

            clientsock.close()
            s.close()
        finally:
            os.chdir(oldcwd)
Beispiel #4
0
 def test_buffer_or_unicode(self):
     # Test that send/sendall/sendto accept a buffer or a unicode as arg
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # XXX temporarily we use python.org to test, will have more robust tests
     # in the absence of a network connection later when more parts of the
     # socket API are implemented.  Currently skip the test if there is no
     # connection.
     try:
         s.connect(("www.python.org", 80))
     except _socket.gaierror as ex:
         skip("GAIError - probably no connection: %s" % str(ex.args))
     exc = raises(TypeError, s.send, None)
     assert str(exc.value) == "must be string or buffer, not None"
     assert s.send(buffer('')) == 0
     assert s.sendall(buffer('')) is None
     assert s.send(memoryview('')) == 0
     assert s.sendall(memoryview('')) is None
     assert s.send(u'') == 0
     assert s.sendall(u'') is None
     raises(UnicodeEncodeError, s.send, u'\xe9')
     s.close()
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM, 0)
     s.sendto(buffer(''), ('localhost', 9)) # Send to discard port.
     s.close()
Beispiel #5
0
 def test_bigport(self):
     import _socket
     s = _socket.socket()
     exc = raises(OverflowError, s.connect, ("localhost", -1))
     assert "port must be 0-65535." in str(exc.value)
     exc = raises(OverflowError, s.connect, ("localhost", 1000000))
     assert "port must be 0-65535." in str(exc.value)
     s = _socket.socket(_socket.AF_INET6)
     exc = raises(OverflowError, s.connect, ("::1", 1234, 1048576))
     assert "flowinfo must be 0-1048575." in str(exc.value)
Beispiel #6
0
 def test_buffer(self):
     # Test that send/sendall/sendto accept a buffer as argument
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # XXX temporarily we use codespeak to test, will have more robust tests in
     # the absence of a network connection later when mroe parts of the socket
     # API are implemented.
     s.connect(("codespeak.net", 80))
     s.send(buffer(''))
     s.sendall(buffer(''))
     s.close()
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM, 0)
     s.sendto(buffer(''), ('localhost', 9)) # Send to discard port.
     s.close()
Beispiel #7
0
def bind(address, sock_type):
    family, addr = addrinfo(address)
    if isinstance(addr, int):
        _sock = _socket.fromfd(addr, family, sock_type)
        _sock.setblocking(0)
        activated = 1
    else:
        _sock = _socket.socket(family, sock_type)
        _sock.setblocking(0)
        activated = 0
        if _socket.AF_INET6 == family and '::' == addr[0]:
            _sock.setsockopt(_socket.IPPROTO_IPV6, _socket.IPV6_V6ONLY, 0)
        _sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
        _sock.bind(addr)
    server_address = _sock.getsockname()
    if isinstance(server_address, tuple):
        host, server_port = server_address
        server_name = getfqdn(host)
    else:
        server_port = server_name = None
    return {'server_address': server_address,
            'server_name'   : server_name,
            'server_port'   : server_port,
            'sock_family'   : family,
            'sock_type'     : sock_type,
            'activated'     : activated,
            '_sock'         : _sock}
Beispiel #8
0
 def accept_client(self):
     BUFSIZE = 1024
     ADDR = (self.server_data.host, self.server_data.port)
     
     self.tcpServerSock = socket(AF_INET, SOCK_STREAM)
     self.tcpServerSock.bind(ADDR)
     self.tcpServerSock.listen(10)
     
     while self.accept_connect:
         # 接受连接必须处于循环提内部,不然只能接受一个请求
         # 这里会阻塞啊,怎么让他停住呢?
         tcpClientSock, _ = self.tcpServerSock.accept()
         
         def communicate():
             # 读取数据不应该加锁,不然会很浪费资源
             data = tcpClientSock.recv(BUFSIZE)
             # 这里应该加锁,
             Server.print_mutex.acquire()
             print data
             # 释放锁
             Server.print_mutex.release()
             
         # 这里也应该创建一个子线程进行通信
         thread = threading.Thread(target = communicate, args = ())
         # 开启子线程,这个线程也应该在某处join
         thread.start()
         # 添加进子线程列表
         self.work_threads.append(thread)
         
         # 这里应该加锁
         Server.mutex.acquire()
         # 增加负载
         self.add_load()
         # 释放锁
         Server.mutex.release()
Beispiel #9
0
 def __init__(self, widget):
     super(AIHome, self).__init__()
     try:
         self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     except socket.error, e:
         print "Strange error creating socket: %s" % e
         return
Beispiel #10
0
    def test_alarm_raise(self):
        try:
            from signal import alarm, signal, SIG_DFL, SIGALRM
        except ImportError:
            skip("no SIGALRM on this platform")
        import _socket
        class Alarm(Exception):
            pass
        def handler(*a):
            raise Alarm()

        s = _socket.socket()
        s.listen(1)
        try:
            signal(SIGALRM, handler)
            alarm(1)
            try:
                s.accept()
            except Alarm:
                pass
            else:
                raise Exception("should have raised Alarm")
            alarm(0)
        finally:
            signal(SIGALRM, SIG_DFL)
Beispiel #11
0
 def test_socket_close_error(self):
     import _socket, os
     if os.name == 'nt':
         skip("Windows sockets are not files")
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     os.close(s.fileno())
     raises(_socket.error, s.close)
Beispiel #12
0
 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
     self._sock = _socket.socket(family, type, proto, fileno)
     self._io_refs = 0
     self._closed = False
     self._sock.setblocking(0)
     self.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
     self.timeout = _socket.getdefaulttimeout()
 def __init__(self, host, port):
     self.socket = _socket.socket()
     self.socket.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, True)
     self.socket.connect((host, port))
     self.map_name = None
     self.tiles_x_y = None
     self.waypoints = None
     self.starting_direction = None
Beispiel #14
0
 def test_socket_connect_ex(self):
     import _socket
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # The following might fail if the DNS redirects failed requests to a
     # catch-all address (i.e. opendns).
     # Make sure we get an app-level error, not an interp one.
     raises(_socket.gaierror, s.connect_ex, ("wrong.invalid", 80))
     s.close()
Beispiel #15
0
 def test_connect_to_kernel_netlink_routing_socket(self):
     import _socket, os
     s = _socket.socket(_socket.AF_NETLINK, _socket.SOCK_DGRAM, _socket.NETLINK_ROUTE)
     assert s.getsockname() == (0, 0)
     s.bind((0, 0))
     a, b = s.getsockname()
     assert a == os.getpid()
     assert b == 0
Beispiel #16
0
 def test_socket_close(self):
     import _socket
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     assert s.fileno() >= 0
     s.close()
     assert s.fileno() < 0
     s.close()
Beispiel #17
0
 def test_readinto_error(self):
     import _socket, posix, array
     s = _socket.socket()
     buff = array.array("c", "X" * 65)
     fh = posix.fdopen(posix.dup(s.fileno()), 'rb')
     # "Transport endpoint is not connected"
     raises(IOError, fh.readinto, buff)
     fh.close()
     s.close()
Beispiel #18
0
def main():
    port = 10500
    s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
    s.bind(('',port))
    s.listen(5)
    while True:
        aso, addr = s.accept()
        threading.Thread(target=connectTarget, args=(aso,)).start()
        print "%s has connected now." % addr[0]
    def connect(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
        s.bind((HOST, 0))

        s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

        s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

        return s
Beispiel #20
0
    def test_async_closed(self):
        import _ssl, _socket

        s = _socket.socket()
        s.settimeout(3)
        ss = _ssl.sslwrap(s, 0)
        s.close()
        exc = raises(_ssl.SSLError, ss.write, "data")
        assert exc.value.strerror == "Underlying socket has been closed."
Beispiel #21
0
 def test_socket_track_resources(self):
     import _socket, os, gc, sys, cStringIO
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     assert s.fileno() >= 0
     s.close()
     assert s.fileno() < 0
     s.close()
     if os.name != 'nt':
         raises(OSError, os.close, fileno)
Beispiel #22
0
 def test_socket_close(self):
     import _socket, errno
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     s.close()
     s.close()
     try:
         s.fileno()
     except _socket.error, ex:
         assert ex.args[0], errno.EBADF
Beispiel #23
0
 def test_socket_connect(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # it would be nice to have a test which works even if there is no
     # network connection. However, this one is "good enough" for now. Skip
     # it if there is no connection.
     try:
         s.connect(("www.python.org", 80))
     except _socket.gaierror, ex:
         skip("GAIError - probably no connection: %s" % str(ex.args))
Beispiel #24
0
 def test_socket_track_resources(self):
     import _socket, os, gc, sys, cStringIO
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     assert s.fileno() >= 0
     s.close()
     assert s.fileno() < 0
     s.close()
     if os.name != 'nt':
         raises(OSError, os.close, fileno)
Beispiel #25
0
 def test_async_closed(self):
     import _ssl, _socket, gc
     s = _socket.socket()
     s.settimeout(3)
     ss = _ssl.sslwrap(s, 0)
     s.close()
     exc = raises(_ssl.SSLError, ss.write, "data")
     assert exc.value.strerror == "Underlying socket has been closed."
     del exc, ss, s
     gc.collect()     # force the destructor() to be called now
Beispiel #26
0
 def test_socket_close(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     assert s.fileno() >= 0
     s.close()
     assert s.fileno() < 0
     s.close()
     if os.name != 'nt':
         raises(OSError, os.close, fileno)
Beispiel #27
0
 def test_convert_between_tuple_and_sockaddr_ll(self):
     import _socket
     s = _socket.socket(_socket.AF_PACKET, _socket.SOCK_RAW)
     assert s.getsockname() == ('', 0, 0, 0, '')
     s.bind(('lo', 123))
     a, b, c, d, e = s.getsockname()
     assert (a, b, c) == ('lo', 123, 0)
     assert isinstance(d, int)
     assert isinstance(e, str)
     assert 0 <= len(e) <= 8
Beispiel #28
0
 def test_socket_close(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     assert s.fileno() >= 0
     s.close()
     assert s.fileno() < 0
     s.close()
     if os.name != 'nt':
         raises(OSError, os.close, fileno)
Beispiel #29
0
 def test_socket_connect(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # XXX temporarily we use codespeak to test, will have more robust tests in
     # the absence of a network connection later when mroe parts of the socket
     # API are implemented.
     s.connect(("codespeak.net", 80))
     name = s.getpeername() # Will raise socket.error if not connected
     assert name[1] == 80
     s.close()
Beispiel #30
0
 def test_convert_between_tuple_and_sockaddr_ll(self):
     import _socket
     s = _socket.socket(_socket.AF_PACKET, _socket.SOCK_RAW)
     assert s.getsockname() == ('', 0, 0, 0, '')
     s.bind(('lo', 123))
     a, b, c, d, e = s.getsockname()
     assert (a, b, c) == ('lo', 123, 0)
     assert isinstance(d, int)
     assert isinstance(e, str)
     assert 0 <= len(e) <= 8
Beispiel #31
0
 def test_socket_connect(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # XXX temporarily we use codespeak to test, will have more robust tests in
     # the absence of a network connection later when mroe parts of the socket
     # API are implemented.
     s.connect(("codespeak.net", 80))
     name = s.getpeername()  # Will raise socket.error if not connected
     assert name[1] == 80
     s.close()
Beispiel #32
0
 def test_socket_connect(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # it would be nice to have a test which works even if there is no
     # network connection. However, this one is "good enough" for now. Skip
     # it if there is no connection.
     try:
         s.connect(("www.python.org", 80))
     except _socket.gaierror, ex:
         skip("GAIError - probably no connection: %s" % str(ex.args))
Beispiel #33
0
    def test_socket_get_values_from_fd(self):
        import _socket
        if hasattr(_socket, "SOCK_DGRAM"):
            s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM)
            try:
                s.bind(('localhost', 0))
                fd = s.fileno()
                s2 = _socket.socket(fileno=fd)
                try:
                    # detach old fd to avoid double close
                    s.detach()
                    assert s2.fileno() == fd
                    assert s2.family == _socket.AF_INET
                    assert s2.type == _socket.SOCK_DGRAM

                finally:
                    s2.close()
            finally:
                s.close()
Beispiel #34
0
 def test_hostname_unicode(self):
     import _socket
     domain = u"испытание.pythontest.net"
     _socket.gethostbyname(domain)
     _socket.gethostbyname_ex(domain)
     _socket.getaddrinfo(domain, 0, _socket.AF_UNSPEC, _socket.SOCK_STREAM)
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
     s.connect((domain, 80))
     s.close()
     raises(TypeError, s.connect, (domain + '\x00', 80))
Beispiel #35
0
 def test_socket_close(self):
     import _socket, errno
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     fileno = s.fileno()
     s.close()
     s.close()
     try:
         s.fileno()
     except _socket.error, ex:
         assert ex.args[0], errno.EBADF
Beispiel #36
0
 def test_async_closed(self):
     import _ssl, _socket, gc
     s = _socket.socket()
     s.settimeout(3)
     ss = _ssl.sslwrap(s, 0)
     s.close()
     exc = raises(_ssl.SSLError, ss.write, "data")
     assert exc.value.strerror == "Underlying socket has been closed."
     del exc, ss, s
     gc.collect()     # force the destructor() to be called now
 def connect(self):
     import _socket
     
     # For fixing #503
     sock = _socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.connect((self.host, self.port))
     # Change this to certicate paths where you have your SSL client certificates
     # to be able to download URLs producing SSL errors.
     ssl = socket.ssl(sock, None, None)
     
     self.sock = httplib.FakeSocket(sock, ssl)
Beispiel #38
0
def ntp_time_f(host="pool.ntp.org", port=123):
    NTP_PACKET_FORMAT = "!12I"
    NTP_DELTA = 2208988800  # 1970-01-01 00:00:00
    NTP_QUERY = '\x1b' + 47 * '\0'

    with closing(socket(AF_INET, SOCK_DGRAM)) as s:
        s.sendto(NTP_QUERY, (host, port))
        msg, address = s.recvfrom(1024)
    unpacked = struct.unpack(NTP_PACKET_FORMAT,
                             msg[0:struct.calcsize(NTP_PACKET_FORMAT)])
    return unpacked[10] + float(unpacked[11]) / 2 ** 32 - NTP_DELTA
Beispiel #39
0
 def test_socket_sharelocal(self):
     import _socket, sys, os
     assert hasattr(_socket.socket, 'share')
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
     with raises(OSError):
         s.listen()
     s.bind(('localhost', 0))
     s.listen(1)
     data = s.share(os.getpid())
     # emulate socket.fromshare
     s2 = _socket.socket(0, 0, 0, data)
     try:
         assert s.gettimeout() == s2.gettimeout()
         assert s.family == s2.family
         assert s.type == s2.type
         if s.proto != 0:
             assert s.proto == s2.proto
     finally:
         s.close()
         s2.close()
Beispiel #40
0
    def __init__(self, host, port):
        self.socket = _socket.socket()
        self.socket.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, True)
        self.socket.connect((host, port))

        self.previous_players = None
        self.previous_player_by_id = {}
        self.previous_facilities = None
        self.previous_facility_by_id = {}
        self.terrain_by_cell_x_y = None
        self.weather_by_cell_x_y = None
Beispiel #41
0
 def test_connect_to_kernel_netlink_routing_socket(self):
     import _socket, os
     if not hasattr(_socket, 'AF_NETLINK'):
         skip("no AF_NETLINK on this platform")
     s = _socket.socket(_socket.AF_NETLINK, _socket.SOCK_DGRAM,
                        _socket.NETLINK_ROUTE)
     assert s.getsockname() == (0, 0)
     s.bind((0, 0))
     a, b = s.getsockname()
     assert a == os.getpid()
     assert b == 0
Beispiel #42
0
 def __init__(self, host=None, port=None):
     if (config.with_viewer):
         self._socket = _socket.socket()
         self._socket.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY,
                                 True)
         if host is None:
             host = "127.0.0.1"
             port = 9111
         self._socket.connect((host, port))
     else:
         self._socket = None
Beispiel #43
0
 def test_socket_connect(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # XXX temporarily we use python.org to test, will have more robust tests
     # in the absence of a network connection later when more parts of the
     # socket API are implemented.  Currently skip the test if there is no
     # connection.
     try:
         s.connect(("www.python.org", 80))
     except _socket.gaierror, ex:
         skip("GAIError - probably no connection: %s" % str(ex.args))
Beispiel #44
0
 def make_listener(self, address, backlog=None):
     if backlog is None:
         backlog = self.backlog
     sock = socket.socket()
     try:
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1)
     except socket.error:
         pass
     sock.bind(address)
     sock.listen(backlog)
     sock.setblocking(False)
     return sock
Beispiel #45
0
 def test_convert_between_tuple_and_sockaddr_ll(self):
     import _socket
     if not hasattr(_socket, 'AF_PACKET'):
         skip("no AF_PACKET on this platform")
     s = _socket.socket(_socket.AF_PACKET, _socket.SOCK_RAW)
     assert s.getsockname() == ('', 0, 0, 0, b'')
     s.bind(('lo', 123))
     a, b, c, d, e = s.getsockname()
     assert (a, b, c) == ('lo', 123, 0)
     assert isinstance(d, int)
     assert isinstance(e, str)
     assert 0 <= len(e) <= 8
Beispiel #46
0
 def test_socket_repr(self):
     import _socket
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
     try:
         expected = ('<socket object, fd=%s, family=%s, type=%s, protocol=%s>'
                     % (s.fileno(), s.family, s.type, s.proto))
         assert repr(s) == expected
     finally:
         s.close()
     expected = ('<socket object, fd=-1, family=%s, type=%s, protocol=%s>'
                 % (s.family, s.type, s.proto))
     assert repr(s) == expected
Beispiel #47
0
 def test_socket_connect_typeerrors(self):
     tests = [
         "",
         ("80"),
         ("80", "80"),
         (80, 80),
     ]
     import _socket
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     for args in tests:
         raises((TypeError, ValueError), s.connect, args)
     s.close()
Beispiel #48
0
 def test_socket_ioctl(self):
     import _socket, sys
     if sys.platform != 'win32':
         skip("win32 only")
     assert hasattr(_socket.socket, 'ioctl')
     assert hasattr(_socket, 'SIO_RCVALL')
     assert hasattr(_socket, 'RCVALL_ON')
     assert hasattr(_socket, 'RCVALL_OFF')
     assert hasattr(_socket, 'SIO_KEEPALIVE_VALS')
     s = _socket.socket()
     raises(ValueError, s.ioctl, -1, None)
     s.ioctl(_socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
Beispiel #49
0
    def connect(self):
        # 得到负载最小的服务器
        server_data = self.proxy.balance_load(self.proxy.get_server_datas())
        # 从服务器信息中提取出ip和端口,拼成地址
        ADDR = (server_data.host, server_data.port)
        #         BUFSIZE = 1024
        # 建立套接字
        self.tcpClientSock = socket(AF_INET, SOCK_STREAM)
        self.tcpClientSock.connect(ADDR)

        # 这里就不用循环发送消息了,直接发送一句话就好了
        self.tcpClientSock.send(self.name + " connected %d" % server_data.port)
def tcpClient():
    clisock = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
    clisock.connect(('localhost', 3491))
    suuid = uuid.uuid1().__str__()
    for i in range(1, 1000):
        header = message.frameheader(msg_id=i, message= suuid)
        (_, buf) = message.wrapptobinary(header)
#        print binascii.hexlify(buf)
        clisock.send(buf)
        time.sleep(0.5)
    clisock.close()
    print "---------------------------------------------"
Beispiel #51
0
 def test_socket_ioctl(self):
     import _socket, sys
     if sys.platform != 'win32':
         skip("win32 only")
     assert hasattr(_socket.socket, 'ioctl')
     assert hasattr(_socket, 'SIO_RCVALL')
     assert hasattr(_socket, 'RCVALL_ON')
     assert hasattr(_socket, 'RCVALL_OFF')
     assert hasattr(_socket, 'SIO_KEEPALIVE_VALS')
     s = _socket.socket()
     raises(ValueError, s.ioctl, -1, None)
     s.ioctl(_socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
Beispiel #52
0
 def test_getsetsockopt_zero(self):
     # related to issue #2561: when specifying the buffer size param:
     # if 0 or None, should return the setted value,
     # otherwise an empty buffer of the specified size
     import _socket
     s = _socket.socket()
     assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 0) == 0
     assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY,
                         2) == b'\x00\x00'
     s.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, True)
     assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 0) == 1
     s.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
     assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 0) == 1
Beispiel #53
0
 def test_socket_connect(self):
     import _socket, os
     s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
     # it would be nice to have a test which works even if there is no
     # network connection. However, this one is "good enough" for now. Skip
     # it if there is no connection.
     try:
         s.connect(("www.python.org", 80))
     except _socket.gaierror as ex:
         skip("GAIError - probably no connection: %s" % str(ex.args))
     name = s.getpeername()  # Will raise socket.error if not connected
     assert name[1] == 80
     s.close()
Beispiel #54
0
 def test_async_closed(self):
     import _ssl, _socket, sys, gc
     s = _socket.socket()
     s.settimeout(3)
     if sys.version_info < (2, 7, 9):
         ss = _ssl.sslwrap(s, 0)
     else:
         ss = _ssl._SSLContext(_ssl.PROTOCOL_TLS)._wrap_socket(s, 0)
     s.close()
     exc = raises(_ssl.SSLError, ss.write, "data")
     assert exc.value.message == 'Underlying socket has been closed.'
     del exc, ss, s
     gc.collect()  # force the destructor() to be called now
Beispiel #55
0
 def test_sslwrap(self):
     import _ssl, _socket, sys, gc
     if sys.platform == 'darwin' or 'freebsd' in sys.platform:
         skip("hangs indefinitely on OSX & FreeBSD (also on CPython)")
     s = _socket.socket()
     ss = _ssl.sslwrap(s, 0)
     exc = raises(_socket.error, ss.do_handshake)
     if sys.platform == 'win32':
         assert exc.value.errno == 10057 # WSAENOTCONN
     else:
         assert exc.value.errno == 32 # Broken pipe
     del exc, ss, s
     gc.collect()     # force the destructor() to be called now
Beispiel #56
0
        def __init__(self,
                     family=AF_INET,
                     type=SOCK_STREAM,
                     proto=0,
                     fileno=None):

            self._sock = _socket.socket(family, type, proto, fileno)

            self._io_refs = 0
            self._closed = False
            self._sock.setblocking(0)
            self.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
            self.timeout = _socket.getdefaulttimeout()
Beispiel #57
0
def _tcp_listener(address, backlog=50, reuse_addr=None):
    """A shortcut to create a TCP socket, bind it and put it into listening state.

    The difference from :meth:`gevent.socket.tcp_listener` is that this function returns
    an unwrapped :class:`_socket.socket` instance.
    """
    sock = _socket.socket()
    if reuse_addr is not None:
        sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr)
    sock.bind(address)
    sock.listen(backlog)
    sock.setblocking(0)
    return sock
Beispiel #58
0
 def test_getsockopt_bad_length(self):
     import _socket
     s = _socket.socket()
     buf = s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1024)
     if len(buf) == 1:
         # win32 returns a byte-as-bool
         assert buf == b'\x00'
     else:
         assert buf == b'\x00' * 4
     raises(_socket.error, s.getsockopt, _socket.IPPROTO_TCP,
            _socket.TCP_NODELAY, 1025)
     raises(_socket.error, s.getsockopt, _socket.IPPROTO_TCP,
            _socket.TCP_NODELAY, -1)