从服务器向客户端发送消息时没有问题
但是从客户端向服务器发送时不能立即显示 只有在服务器发送完一条才有客户端发送的上一条
客户端:
import socket
import threading
def talk(s):
while True:
data=input()
s.send(data.encode('utf-8'))
if data=='exit':
break
s.close()
def receive(s):
while True:
data=s.recv(1024)
if not data or data.decode('utf-8') == 'exit':
break
print(data.decode('utf-8'))
s.close()
print('886')
if name == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8999))
print(s.recv(1024).decode('utf-8'))
r=threading.Thread(target=receive,args=(s,))
t=threading.Thread(target=talk,args=(s,))
t.start()
r.start()
服务器:
import socket
import threading
def receive(s,addr):
while True:
data=s.recv(1024)
if not data or data.decode('utf-8') == 'exit':
break
print(data.decode('utf-8'))
s.close()
print('886 %s %s'%addr)
def talk(s):
while True:
data=input()
s.send(data.encode('utf-8'))
if data=='exit':
break
s.close()
if __name__=='__main__':
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',8999))
s.listen(5)
print('waiting for connection...')
while True:
sock,addr=s.accept()
print('找到一个新的连接:%s:%s'%addr)
sock.send(b'hello ')
t=threading.Thread(target=talk,args=(sock,))
r=threading.Thread(target=receive,args=(sock,addr))
r.start()
t.start()