zoukankan      html  css  js  c++  java
  • python3(socket 实现udp,tcp套接字编程)

    #coding=utf-8
    #客户端程序TCP 连接
    
    import socket
    
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    s.connect(('127.0.0.1',9999))
    
    print(s.recv(1024))
    
    for data in ['Michael','Tracy','Sarah']:
        s.send(data.encode())
        print(s.recv(1024))
    
    s.send(b'exit')
    复制代码
    复制代码
    #coding=utf-8
    #TCP服务器端程序
    import socket
    import time
    import threading
    
    
    
    def tcplink(sock,addr):
        print("accept new connection from %s:%s..." % addr)
        sock.send("Welcom!".encode())
        while True:
            data=sock.recv(1024)
            time.sleep(1)
            if data=='exit' or not data:
                break
            sock.send("hello: ".encode()+data)
        sock.close()
        print("Connection from %s:%s closed." % addr)
        
        
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  # 创建一个基于ipv4 的TCP协议的socket
    
    s.bind(('127.0.0.1',9999))  #监听端口
    
    s.listen(5)
    print("Waiting for connection......")
    
    while True:
        sock,addr=s.accept()
        t=threading.Thread(target=tcplink,args=(sock, addr))
        t.start()
        
    复制代码

    运行结果:

    Waiting for connection......
    accept new connection from 127.0.0.1:60218...
    Connection from 127.0.0.1:60218 closed.
    b'Welcom!'
    b'hello: Michael'
    b'hello: Tracy'
    b'hello: Sarah'

    UDP客户端和服务器端代码:


    复制代码
    #coding=utf-8
    #UDP 客户端代码
    
    import socket
    
    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    
    for data in ["chenshan","yuanhui","chendianqiang"]:
        s.sendto(data.encode(),('127.0.0.1',9999))
        print(s.recv(1024))
        
    s.close()
    复制代码
    复制代码
    #coding=utf-8
    #UDP 协议服务器代码
    import socket
    
    s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    
    s.bind(('127.0.0.1',9999))
    print("Bind UDP on prot:9999")
    
    while True:
        data,addr=s.recvfrom(1024)
        print("Receive from %s:%s"% addr)
        s.sendto("Hello ".encode()+data,addr)
    复制代码
  • 相关阅读:
    [五]SpringMvc学习-Restful风格实现
    [四]SpringMvc学习-对servlet与json的支持与实现
    [三]SpringMvc学习-封装、乱码问题、重定向、转发
    Android-aidl, binder,surfaceview
    linux memory dump--http://www.forensicswiki.org/wiki/Tools:Memory_Imaging
    Vanish/squid
    dongle --NFC
    词频统计 in office
    各种小巧的Hello World
    程序入口函数和glibc及C++全局构造和析构
  • 原文地址:https://www.cnblogs.com/jjj-fly/p/7905464.html
Copyright © 2011-2022 走看看