我在TCP python socket prog中遇到以下代码问题。我试图从(比方说)3个客户端发送整数消息。因此,有3个客户端,因此代理知道N = 3,它将等到收到3个数字。第一个客户端向代理发送10,第二个客户端向代理发送20,第三个客户端向代理发送30。因为已到达N,代理开始传输到服务器。它将发送(按顺序):10,20,30,END(其中每个逗号表示一条新消息)。服务器接收4条消息,收到END消息后,开始计算平均值。平均值为20,因此服务器向代理发送20,并关闭连接。代理接收20,并将其发送到所有3个客户端,然后关闭连接。客户收到20。
请检查下面的代码并让我知道我在哪里犯错误...我能够从客户端发送号码但没有从代理/服务器获得响应。我有什么不对吗?
对于客户:
#!/usr/bin/env python
import socket
HOST = 'localhost'
PORT = 21001
proxysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxysock.connect((HOST, PORT))
while True:
try:
data = str(raw_input())
except valueError:
print 'invalid number'
proxysock.sendall(data)
data = proxysock.recv(1024)
print 'server reply:' +data
proxysock.close()
For Proxy:
#!/usr/bin/env python
import select
import sys
import socket
from thread import *
HOST = 'localhost'
PORT = 21001
PORT1 = 22000
max_conn = 5
buffer_size = 2048
proxyserversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxyserversock.bind((HOST, PORT))
proxyserversock.listen(max_conn)
input = [proxyserversock,sys.stdin]
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for proxysock in inputready:
if proxysock == proxyserversock:
client_sock, addr = proxyserversock.accept()
input.append(client_sock)
elif proxysock == sys.stdin:
junk = sys.stdin.readline()
running = 0
else:
data = proxysock.recv(buffer_size)
if data:
proxysock.send(data)
else:
proxysock.close()
input.remove(proxysock)
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.connect((HOST, PORT1))
serversock.sendall(data,END)
serversock.recv(buffer_size)
client_sock.sendall()
serversock.close()
client_sock.close()
对于服务器:
#!/usr/bin/env python
import socket
HOST = 'localhost'
PORT1 = 22000
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.bind((HOST, PORT1))
serversock.listen(10)
while 1:
serversock, addr = serversock.accept()
data = serversock.recv(2048)
data.pop()
average = float(sum(data))/len(data)
serversock.sendall(average)
print 'avg' + average
serversock.close()