• [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)

  • 相关阅读:
    codeforces 669C C. Little Artem and Matrix(水题)
    codeforces 669B B. Little Artem and Grasshopper(水题)
    oracle drop table recyclebin恢复
    odu恢复drop表--不通过logmnr挖掘object_id
    odu恢复drop表--通过logmnr挖掘object_id
    odu恢复delete 表
    GO学习-(7) Go语言基础之流程控制
    GO学习-(6) Go语言基础之运算符
    GO学习-(4) Go语言基础之变量和常量
    GO学习-(3) VS Code配置Go语言开发环境
  • 原文地址:https://www.cnblogs.com/share23/p/9822755.html
Copyright © 2020-2023  润新知