服务器
from socket import *
import threading
IP = "localhost"
port = 40005
tcp_server = socket(AF_INET,SOCK_STREAM)
tcp_server.bind((IP, port))
tcp_server.listen(128)
print('listen at port :',port)
socks = []
st = []
def handle():
while True:
for client_socker in socks:
try:
from_client_msg = client_socker.recv(1024)
except Exception as e:
continue
if from_client_msg == 'exit':
break
print('接受到数据 :',from_client_msg.decode("gbk"))
st.append(from_client_msg.decode("gbk"))
send_data = client_socker.send(str(st).encode("gbk"))
t = threading.Thread(target=handle)
if __name__ == '__main__':
t.start()
print()
while True:
client_socker, clientAddr = tcp_server.accept()
print('connected by', clientAddr)
client_socker.setblocking(0)
socks.append(client_socker)
客户端
from socket import *
import sys
IP = "localhost"
port = 40005
tcp_socket = socket(AF_INET, SOCK_STREAM)
try:
tcp_socket.connect((IP,port))
except Exception as e:
print('服务器未启动')
sys.exit()
while True:
send_data = input("请输入发送内容:")
tcp_socket.send(send_data.encode("gbk"))
if send_data == 'exit':
break
try:
from_server_msg = tcp_socket.recv(1024)
data = from_server_msg.decode("gbk")
print('recieved :',data)
except:
pass
tcp_socket.close()