单用户连接:
socket_client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((\'127.0.0.1\', 8000))
while True:
re_data = input()
client.send(re_data.encode(\'utf8\'))
data = client.recv(1024)
print(data.decode(\'utf8\'))
socket_server.py
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((\'0.0.0.0\', 8000))
server.listen()
sock,addr = server.accept()
while True:
data = sock.recv(1024)
print(data.decode(\'utf8\'))
re_data = input()
sock.send(re_data.encode(\'utf8\'))
多用户连接(利用多线程)
socket_server.py
import socket, threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((\'0.0.0.0\', 8000))
server.listen()
def handle_sock(sock, addr):
data = sock.recv(1024)
print(data.decode(\'utf8\'))
re_data = input()
sock.send(re_data.encode(\'utf8\'))
while True:
sock,addr = server.accept()
current_thread = threading.Thread(target=handle_sock, args=(sock,addr))
current_thread.start()