无法与代理/服务器应用程序通信

2021-10-17 17:58:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我对TCP python socket prog中的以下代码有问题。我试图发送整数消息从(假设)3个客户端。所以,有3个客户机,所以代理知道N=3,它将等待,直到它收到3个数字。第一个客户端向代理发送10个,第二个客户端向代理发送20个,第三个客户端向代理发送30个。因为达到N,代理开始向服务器传输。它将发送(按顺序):10、20、30、结束(每个逗号表示一条新消息)。服务器接收到这4条消息,在接收到结束消息之后,它开始计算平均值。平均值是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()

对于代理:

  #!/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()