当前位置: 首页>>代码示例>>Python>>正文


Python socket.socket函数代码示例

本文整理汇总了Python中socket.socket函数的典型用法代码示例。如果您正苦于以下问题:Python socket函数的具体用法?Python socket怎么用?Python socket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了socket函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _create_remote_socket

    def _create_remote_socket(self, ip, port):
        if self._remote_udp:
            addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
            addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
        else:
            addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if self._forbidden_iplist:
            if common.to_str(sa[0]) in self._forbidden_iplist:
                raise Exception('IP %s is in forbidden list, reject' %
                                common.to_str(sa[0]))
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self

        if self._remote_udp:
            af, socktype, proto, canonname, sa = addrs_v6[0]
            remote_sock_v6 = socket.socket(af, socktype, proto)
            self._remote_sock_v6 = remote_sock_v6
            self._fd_to_handlers[remote_sock_v6.fileno()] = self
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)

        remote_sock.setblocking(False)
        if self._remote_udp:
            pass
        else:
            remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        return remote_sock
开发者ID:konggil,项目名称:shadowsocks,代码行数:33,代码来源:tcprelay.py

示例2: handle

def handle(client_socket, address):
    global totalnewconns
    global mysql_stats
    totalnewconns += 1
    mysql_sockets = []
    # First connection is always master, it gets all modifications
    mysql_socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
    state = "alive"
    try:
        # TODO: add a timer here to wait 10s if a server is dead before
        #       trying to reconnect again
        mysql_socket1.connect(('192.168.127.3', 3306))
        mysql_stats[0]["globalstate"] = "alive"
        state = "alive"
    except socket.error as err:
        mysql_stats[0]["globalstate"] = "dead"
        state = "dead"
    mysql_sockets.append({"conn": mysql_socket1, "state":state, "stats":mysql_stats[0]})
    mysql_socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
    state = "alive"
    try:
        # TODO: add a timer here to wait 10s if a server is dead before
        #       trying to reconnect again
        mysql_socket2.connect(('192.168.127.4', 3306))
        mysql_stats[1]["globalstate"] = "alive"
        state = "alive"
    except socket.error as err:
        mysql_stats[1]["globalstate"] = "dead"
        state = "dead"
    mysql_sockets.append({"conn": mysql_socket2, "state":state, "stats":mysql_stats[1]})
    do_handshake(client_socket, mysql_sockets)
    do_commands(client_socket, mysql_sockets)
开发者ID:alexclear,项目名称:yybal,代码行数:32,代码来源:yybal.py

示例3: send_to_client

 def send_to_client(self, sctag, msg): #msg is json in str
   msg_ = check_smsg('send', sctag, msg)
   if msg_ == None:
     logging.error('msg is not proto-good')
     return
   cp_info = self.commpair_info_dict[sctag]
   proto = cp_info['proto']
   #sock = cp_info['sock']
   sock = None
   c_addr = cp_info['c_addr']
   #
   response = None
   if proto == 'tcp':
     try:
       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       sock.connect(c_addr)
       sock.sendall(msg)
       response = sock.recv(1024)
     except IOError as e:
       if e.errno == errno.EPIPE:
         #due to insuffient recv_buffer at the other end
         logging.error('broken pipe err, check recv_buffer')
     finally:
       sock.close()
   elif proto == 'udp':
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     sock.sendto(msg, c_addr)
     response = sock.recv(1024)
   #
   logging.info('sent to %s_client=%s, datasize=%sBs', proto,c_addr,sys.getsizeof(msg))
   logging.info('response=%s', response)
开发者ID:mfatihaktas,项目名称:sim_rel,代码行数:31,代码来源:control_comm_intf.py

示例4: on_ONLINE_mouseClick

    def on_ONLINE_mouseClick(self, event):
        global ONline
        Switch = self.components.ONLINE.checked
        if Switch == True:
            UDP_IP = self.components.UDP_IP.text
            UDP_PORT = self.components.UDP_PORT.text
            UDP_PORT = int(UDP_PORT)
            time.sleep(1)
            ONline = 1
            self.components.ONLINE.label = "Go Offline"
            #easygui.msgbox("Server>> Online!")
            time.sleep(2)
            sock = socket.socket(socket.AF_INET, # Internet
            socket.SOCK_DGRAM) # UDP
            sock.sendto("Server>> Online!", (UDP_IP, UDP_PORT))

        if Switch == False:
            UDP_IP = self.components.UDP_IP.text
            UDP_PORT = self.components.UDP_PORT.text
            UDP_PORT = int(UDP_PORT)
            time.sleep(1)
            ONline = 0
            self.components.ONLINE.label = "Go Online"
            #easygui.msgbox("Server>> Offline!")
            time.sleep(2)
            sock = socket.socket(socket.AF_INET, # Internet
            socket.SOCK_DGRAM) # UDP
            sock.sendto("Server>> Offline!", (UDP_IP, UDP_PORT))
开发者ID:AnthyG,项目名称:BlubClient,代码行数:28,代码来源:blubclient.py

示例5: getFreeAddresses

    def getFreeAddresses(self):
        import socket
        s = socket.socket()
        s.bind(('',0))
        port0 = s.getsockname()[1]
        
        s1 = socket.socket()
        s1.bind(('',0))
        port1 = s1.getsockname()[1]
        s.close()
        s1.close()
        
        if port0 <= 0 or port1 <= 0:
            #This happens in Jython...
            from java.net import ServerSocket
            s0 = ServerSocket(0)
            port0 = s0.getLocalPort()
            
            s1 = ServerSocket(0)
            port1 = s1.getLocalPort()
            
            s0.close()
            s1.close()

        assert port0 != port1
        assert port0 > 0
        assert port1 > 0
            
        return port0, port1
开发者ID:MrGreen123,项目名称:Pydev,代码行数:29,代码来源:test_pydevconsole.py

示例6: reuse_socket_address

    def reuse_socket_address(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        old_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        print "Old socket state: ", old_state

        # 激活套接字重用
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        new_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        print "New socket state: ", new_state


        local_port = 8282
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srv.bind(('', local_port))
        srv.listen(1)
        print "Listen On Port: ", local_port
        while True:
            try:
                connection, addr = srv.accept()
                print "Connect by %s:%s"%(addr[0],addr[1])
            except KeyboardInterrupt:
                break
            except socket.error, msg:
                print '%s' % msg
开发者ID:Itanq,项目名称:Python_Socket,代码行数:26,代码来源:reuse_socket_address.py

示例7: run

	def run(self):
			while True:
				snap_shot()
				#time.sleep(.05)

				#HOST = 'u1204vm.local'
				#CPORT = 9091
				#MPORT = 9090
				#FILE = sys.argv[1]
				print "sending image"
				cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				cs.connect((self.host, self.cport))
				cs.send("SEND " + self.filetosend)
				cs.close()

				time.sleep(0.05)

				ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				ms.connect((self.host, self.mport))

				f = open(self.filetosend, "rb")
				data = f.read()
				f.close()

				ms.send(data)
				ms.close()
				print "waiting one second before sending another image"
开发者ID:Tfou57,项目名称:robomow,代码行数:27,代码来源:robot_gui.py

示例8: portscan

def portscan(target,ports,tcp,udp,verbose):
    #target=IPaddr,ports=list of ports,tcp=true/false,udp=true/false,verbose=true/false
    printmsg(("Now scanning %s" % (target)))
    tcpports=[]
    udpports=[]
    if tcp:
        for portnum in ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(0.01)
                s.connect((target, portnum))
            except Exception:
                failvar = 0
                if verbose: print "%d/tcp \tclosed" % (portnum)
            else:
                print "%d/tcp \topen"% (portnum)
                tcpports.append(portnum)
            s.close()
    if udp:
        for portnum in ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.settimeout(0.1)
                s.sendto("--TEST LINE--", (target, portnum))
                recv, svr = s.recvfrom(255)
            except Exception, e:
                try: errno, errtxt = e
                except ValueError:
                    print "%d/udp \topen"% (portnum)
                    udpports.append(portnum)
                else:
                    if verbose: print "%d/udp \tclosed" % (portnum)
            s.close()
开发者ID:1989-13428,项目名称:lpd141513428,代码行数:33,代码来源:active.py

示例9: testDefaultTimeout

    def testDefaultTimeout(self):
        # Testing default timeout
        # The default timeout should initially be None
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Set the default timeout to 10, and see if it propagates
        socket.setdefaulttimeout(10)
        self.assertEqual(socket.getdefaulttimeout(), 10)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), 10)
        s.close()

        # Reset the default timeout to None, and see if it propagates
        socket.setdefaulttimeout(None)
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Check that setting it to an invalid value raises ValueError
        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)

        # Check that setting it to an invalid type raises TypeError
        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
开发者ID:249550148,项目名称:gevent,代码行数:27,代码来源:test_socket.py

示例10: minecraft

def minecraft(phenny, input):
    if input.sender.startswith('#'): return phenny.reply("This command only available in private message.")
    # Set up
    s = socket.socket()
    t = socket.socket()
    u = socket.socket()
    v = socket.socket()
    gamerx = cprossu = packethumper = bitviper = "UP"
    
    # Attempt connections
    try:
        s.connect(('gamerxreviews.net', 25565))
    except:
        gamerx = "DOWN"
    try:
        t.connect(('72.222.196.252',25565))
    except:
        cprossu = "DOWN"
    try:
        u.connect(('minecraft.nerderosity.com',25565))
    except:
        packethumper = "DOWN"
    try:
        v.connect(('minecraft.bitviper.org',25565))
    except:
        bitviper = "DOWN"
    
    # output
    phenny.reply( "GuardianZozo's minecraft server: gamerxreviews.net:25565. Server Status: {}".format(gamerx) )
    phenny.reply( "Cprossu's minecraft server: 72.222.196.252:25565. Server Status: {}".format(cprossu) )
    phenny.reply( "PacketHumper's minecraft server: minecraft.nerderosity.com:25565. Server Status: {}".format(packethumper) )
    phenny.reply( "BitViper's minecraft server: minecraft.bitviper.org:25565. Server Status: {}".format(bitviper) )
开发者ID:Steve-V,项目名称:tgg-BotSteve,代码行数:32,代码来源:tgg.py

示例11: create_persistent

def create_persistent(address):

    """
    Create a new process, returning a persistent communications channel between
    the creating process and the created process. This channel can be
    disconnected from the creating process and connected to another process, and
    thus can be used to collect results from daemon processes.

    In order to be able to reconnect to created processes, the 'address' of the
    communications endpoint for the created process needs to be provided. This
    should be a filename.
    """

    parent = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    child = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    child.bind(address)

    for s in [parent, child]:
        s.setblocking(1)

    pid = os.fork()
    if pid == 0:
        parent.close()
        return PersistentChannel(pid, child, address)
    else:
        child.close()
        #parent.connect(address)
        return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0))
开发者ID:ChrisTCH,项目名称:phd_code,代码行数:28,代码来源:pprocess.py

示例12: pick_random_port

def pick_random_port():
    """Bind to an ephemeral port, force it into the TIME_WAIT state, and
    unbind it.

    This means that further ephemeral port alloctions won't pick this
    "reserved" port, but subprocesses can still bind to it explicitly, given
    that they use SO_REUSEADDR.

    By default on linux you have a grace period of 60 seconds to reuse this
    port.

    To check your own particular value:
    $ cat /proc/sys/net/ipv4/tcp_fin_timeout
    60
    """
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('127.0.0.1', 0))
    s.listen(0)

    sockname = s.getsockname()

    # these three are necessary just to get the port into a TIME_WAIT state
    s2 = socket.socket()
    s2.connect(sockname)
    s.accept()

    return sockname[1]
开发者ID:dev-alex-alex2006hw,项目名称:paasta,代码行数:28,代码来源:local_run.py

示例13: createSockByType

 def createSockByType(self, sockType):
     if sockType == socktypes.UDP_CLIENT_LOCAL:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     elif sockType == socktypes.TCP_CLIENT_LOCAL:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     else:
         logger.error("***** ERROR SOCKTYPE *****")
开发者ID:noname007,项目名称:PySockDebuger,代码行数:7,代码来源:SockClient.py

示例14: make_dummy_socket_pair

def make_dummy_socket_pair():
    """Create a pair of sockets connected to each other on the local
    interface.  Used to implement SocketHandler.wakeup().

    On Unixish systems, port 0 will pick the next available port.
    But that appears to have problems on Windows possibly with
    firewall software.  So if we hit a socketerror with port 0, we
    try ports between 50000 and 65500.
    """
    attempts = 0
    port = 0
    family, addr = localhost_family_and_addr()
    while 1:
        attempts += 1
        try:
            dummy_server = socket.socket(family, socket.SOCK_STREAM)
            dummy_server.bind((addr, port))
            dummy_server.listen(1)
            server_address = dummy_server.getsockname()
            first = socket.socket(dummy_server.family, socket.SOCK_STREAM)
            first.connect(server_address)
            second, address = dummy_server.accept()
            dummy_server.close()
            return first, second
        except socket.error:
            # if we hit this, then it's hopeless--give up
            if port > 65500:
                sys.stderr.write(("Tried %s bind attempts and failed on " "addr %s port %d\n") % (attempts, addr, port))
                raise
            # bump us into ephemeral ports if we need to try a bunch
            if port == 0:
                port = 50000
            else:
                port += 10
开发者ID:foxi,项目名称:miro,代码行数:34,代码来源:util.py

示例15: test_get_conns

 def test_get_conns(self):
     sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock1.bind(('127.0.0.1', 0))
     sock1.listen(1)
     sock1ipport = '%s:%s' % sock1.getsockname()
     sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock2.bind(('127.0.0.1', 0))
     sock2.listen(1)
     orig_port = memcached.DEFAULT_MEMCACHED_PORT
     try:
         sock2ip, memcached.DEFAULT_MEMCACHED_PORT = sock2.getsockname()
         sock2ipport = '%s:%s' % (sock2ip, memcached.DEFAULT_MEMCACHED_PORT)
         # We're deliberately using sock2ip (no port) here to test that the
         # default port is used.
         memcache_client = memcached.MemcacheRing([sock1ipport, sock2ip])
         one = two = True
         while one or two:  # Run until we match hosts one and two
             key = uuid4().hex
             for conn in memcache_client._get_conns(key):
                 peeripport = '%s:%s' % conn[2].getpeername()
                 self.assert_(peeripport in (sock1ipport, sock2ipport))
                 if peeripport == sock1ipport:
                     one = False
                 if peeripport == sock2ipport:
                     two = False
     finally:
         memcached.DEFAULT_MEMCACHED_PORT = orig_port
开发者ID:vbaret,项目名称:swift,代码行数:27,代码来源:test_memcached.py


注:本文中的socket.socket函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。