python socket编程tcp/udp俩连接

Posted 来呀来呀

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python socket编程tcp/udp俩连接相关的知识,希望对你有一定的参考价值。

#服务端代码

 

import socket, threading
import time

‘‘‘
#服务端 TCP连接

def tcplink(sock, addr):
    print(‘Accept new connection from %s:%s...‘ % addr)
    sock.send(b‘Welcome!‘)
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode(‘utf-8‘) == ‘exit‘:
            break
        sock.send((‘Hello, %s!‘ % data.decode(‘utf-8‘)).encode(‘utf-8‘))
    sock.close()
    print(‘Connection from %s:%s closed.‘ % addr)


if __name__ == ‘__main__‘:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((‘localhost‘, 9999))
    s.listen(5)
    print(‘Waiting for connecting ...‘)
# while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()
‘‘‘


# 服务端UDP
if __name__ == __main__:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定端口:
    s.bind((127.0.0.1, 9999))
    print(Bind UDP on 9999...)
    while True:
        # 接收数据:
        data, addr = s.recvfrom(1024)
        print(Received from %s:%s. % addr)
        s.sendto(bHello, %s! % data, addr)

 

 

 

 

 

# 客户端代码

import socket

# tcp连接
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((‘127.0.0.1‘, 9999))
# print(s.recv(1024).decode(‘utf-8‘))
# for data in [b‘Micheal‘, b‘Tracy‘, b‘Sarah‘]:
#     s.send(data)
#     print(s.recv(1024).decode(‘utf-8‘))
# s.send(b‘exit‘)
# s.close()
#


# udp连接
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [bMichael, bTracy, bSarah]:
    # 发送数据:
    s.sendto(data, (127.0.0.1, 9999))
    # 接收数据:
    print(s.recv(1024).decode(utf-8))
s.close()

 

 

 

 

  

 

  

 

以上是关于python socket编程tcp/udp俩连接的主要内容,如果未能解决你的问题,请参考以下文章

Python学习之旅(三十四)

Python学习之旅---socket编程(基于TCP/UDP编程)

Python之UDP编程

网络编程TCP/UDP(socket编程)

网络编程TCP/UDP(socket编程)

完全理解TCP/UDPHTTP长连接WebsocketSockJS/Socket.IO以及STOMP的区别和联系