我是Python中套接字连接的服务器和客户端,
客户端:
import socket
import sys
from sys import stdin
serv = 'ip goes here'
port = 8888
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((serv, port))
def prompt():
sys.stdout.write('<You> ')
sys.stdout.flush()
def send(x):
sock.sendall(x)
rec = 0
ex = len(x)
while rec < ex:
data = sock.recv(16)
rec += len(data)
while 1:
if sock:
data = sock.recv(16)
if len(data) == 0:
pass
print '<Server> %s' % data
prompt()
msg = stdin.readline()
sock.sendall(msg)
我现在拥有它的方式,如果你在一个客户端上说一些东西,它会向两个客户端发送“alphabet”,但是其他客户端在发送新消息之前不会收到它,因为它正在等待stdin.readline( ) 发生。我想知道如何使它成为客户端总是从服务器接收数据,并且不必首先发生stdin.readline()就会看到它。
由于
答案 0 :(得分:1)
使用CrazyCasta
建议的线程实现我想要的效果def receiving():
while 1:
if sock:
data = sock.recv(16)
if len(data) == 0:
pass
print '<Server> %s' % data
def sending():
while 1:
msg = stdin.readline()
sock.sendall(msg)
t1 = Thread(target=receiving)
t2 = Thread(target=sending)
t1.start()
t2.start()