标签:end close recv 发送数据 accept __name__ import tin bsp
#服务端代码
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(b‘Hello, %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 [b‘Michael‘, b‘Tracy‘, b‘Sarah‘]: # 发送数据: s.sendto(data, (‘127.0.0.1‘, 9999)) # 接收数据: print(s.recv(1024).decode(‘utf-8‘)) s.close()
标签:end close recv 发送数据 accept __name__ import tin bsp
原文地址:https://www.cnblogs.com/ceshixuexi/p/9082526.html