zoukankan      html  css  js  c++  java
  • [Python_7] Python Socket 编程


    0. 说明

      Python Socket 编程


    1. TCP 协议

      [TCP Server]

      通过 netstat -ano 查看端口是否开启

    # -*-coding:utf-8-*-
    
    """
        TCP 协议的 Socket 编程,Server 端
        Server 端绑定到指定地址,监听特定的端口,接受发来的连接请求
    """
    import threading
    import socket
    import time
    
    
    class CommThread(threading.Thread):
        def run(self):
            while True:
                # 接受数据
                data = sock.recv(4096)
                print("收到了%s = %s" % (str(self.addr), str(data)), )
    
        def __init__(self, sock, addr):
            threading.Thread.__init__(self)
            self.sock = sock
            self.addr = addr
    
    
    # 创建服务器套接字,绑定端口
    ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ss.bind(("127.0.0.1", 8888))
    ss.listen(0)
    
    while True:
        sock, addr = ss.accept()
        CommThread(sock, addr).start()
        print("%s链接进来
    " % (str(addr)), )
        time.sleep(1)

      [TCP Client]

    # -*-coding:utf-8-*-
    """
        TCP 协议的 Socket 编程,Client 端
    """
    import threading
    import socket
    import time
    
    # 创建服务器套接字,绑定端口
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("127.0.0.1" , 8888))
    
    i = 1
    while True:
        str = "tom%d
    " % (i)
        print ("client : " + str),
        sock.send(bytes(str,'utf-8'))
        time.sleep(1)
        i += 1

    2. UDP 协议

      [UDP Server]

    # -*-coding:utf-8-*-
    
    """
        UDP 协议的 Socket 编程,Server 端
    """
    import socket
    
    # 创建 UDP 接收方
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("192.168.13.6", 9999))
    
    i = 1
    while True:
        data = sock.recv(4096)
        print(str(data))

      [UDP Client]

    # -*-coding:utf-8-*-
    """
        UDP 协议的 Socket 编程,Client 端
    """
    
    import socket
    import time
    
    # 创建 UDP 发送方
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("192.168.13.6", 8888))
    
    i = 1
    while True:
        sock.sendto(bytes(("tom" + str(i)),'utf-8'), ("192.168.13.255", 9999))
        i += 1
        time.sleep(1)

  • 相关阅读:
    Python爬虫连载9-JS加密之“盐”​、ajax请求
    Java连载86-List集合详解
    HTML连载69-透视属性以及其他属性练习
    Java连载85-集合的Contains和Remove方法
    Python爬虫连载8-JS加密(一)
    Java连载84-Collection的常用方法、迭代器
    HTML连载68-形变中心点、形变中心轴
    Java连载83-单向链表、双向链表、collections常用方法
    [刷题] 447 Number of Boomerangs
    [刷题] 454 4Sum II
  • 原文地址:https://www.cnblogs.com/share23/p/9822755.html
Copyright © 2011-2022 走看看