server
#!/usr/bin/env python # -*- coding:utf-8 -*- import socket import threading # AF_INET IPv4 SOCK_STREAM TCP协议 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('0.0.0.0', 7777)) server.listen() def handle_sock(sock, addr): while True: data = sock.recv(1024) print(data.decode('utf-8')) if 'bye' in data.decode('utf-8'): break re_data = input() sock.send(re_data.encode('utf-8')) sock.close() # 获取从客户端发送的数据,一次获取1K的数据 while True: sock, addr = server.accept() # 用线程去处理新接收的连接(用户) client_thread = threading.Thread(target=handle_sock, args=(sock, addr)) client_thread.start() # data = sock.recv(1024) # print(data.decode('utf-8')) # re_data = input() # sock.send(re_data.encode('utf-8')) # sock.close() # server.close()
client
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import socket 5 6 7 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 client.connect(('127.0.0.1',7777)) 9 while True: 10 re_data = input() 11 client.send(re_data.encode('utf-8')) 12 data = client.recv(1024) 13 print(data.decode('utf-8'))
server
client1 server1 client2 server2 bye client1 server1
client1
client1 server1 client1 server1
client2
client2 server2 bye