美文网首页
udp和tcp笔记

udp和tcp笔记

作者: lk_erzanml | 来源:发表于2021-02-06 11:05 被阅读0次
    #UDP
    from threading import Thread
    import socket
    u=socket.socket(socket.AF_INET,socket.SOCK_DGRAM )
    u.bind((“127.0.0.1”,8888))#绑定端口,用来接收数据
    def sendnews():
        while True:
            data=input()
            u.sendto(data.encode(“gbk”), (“127.0.0.1”,8888))
    def recvnews():
        while True:
        data,ip=u.recvfrom (1024)
        print(data.decode(“gbk”))
    t1=Thread(target=sendnews,args=())
    t2=Thread(target=recvnews,args=())
    t1.start()
    t2.start()
    #TCP
    #服务端
    from threading import Thread 
    import socket
    t=socket.socekt(socket.AF_INET,socket.SOCK_STREAM )
    t.bind((“127.0.0.1”,8888))
    b.listen(5) 
    def sendnews():
        while True:
            data=input()
            new_t.send(data.encode(“gbk”))
    def recvnews():
        while True:
            data=new_t.recv()
            print(data.decode(“gbk”))
    
    if __name__==”__main__”:
        while True:
            new_t,ip=t.accept() 
            t1=Thread(target=sendnews,args=())
    t2=Thread(target=recvnews,args=())
    t1.start()
    t2.start()
    #客户端
    from threading import Thread 
    import socket
    t=socket.socekt(socket.AF_INET,socket.SOCK_STREAM )
    ipport=(“127.0.0.1”,8888)
    t.connect(ipport) 
    def sendnews():
        while True:
            data=input()
            t.send(data.encode(“gbk”))
    def recvnews():
        while True:
            data= t.recv()
            print(data.decode(“gbk”))
    
    t1=Thread(target=sendnews,args=())
    t2=Thread(target=recvnews,args=())
    t1.start()
    t2.start()
    
    
    

    相关文章

      网友评论

          本文标题:udp和tcp笔记

          本文链接:https://www.haomeiwen.com/subject/hvazaktx.html