Python Server发送数据不起作用

时间:2012-09-19 06:25:38

标签: python client-server

我目前正在使用Python的服务器,我面临的问题是客户端无法从服务器检索发送的数据。

服务器的代码是:

import sys
import socket
from threading import Thread

allClients=[]

class Client(Thread):

    def __init__(self,clientSocket):
                Thread.__init__(self)
                self.sockfd = clientSocket #socket client
                self.name = ""
                self.nickName = ""

    def newClientConnect(self):

      allClients.append(self.sockfd)
      while True:
            while True:
                try:
                    rm= self.sockfd.recv(1024)
                    print rm

                    try:
                        self.sockfd.sendall("\n Test text to check send.")
                        print "Data send successfull"
                        break


                    except socket.error, e:
                        print "Could not send data"

                    break

                except ValueError:
                       self.sockfd.send("\n Could not connect properly")


    def run(self):
                self.newClientConnect()
                self.sockfd.close() 
                while True:
                        buff = self.sockfd.recv(1024)

                        if buff.strip() == 'quit':
                            self.sockfd.close()
                            break # Exit when break
                        else:
                            self.sendAll(buff)
#Main
if __name__ == "__main__":

    #Server Connection to socket:
    IP = '127.0.0.1'
    PORT = 80
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)

    print ("Server Started")
    try:
        serversocket.bind(('',5000))
    except ValueError,e:
        print e
    serversocket.listen(5)

while True:
        (clientSocket, address) = serversocket.accept()
        print 'New connection from ', address
        ct = Client(clientSocket)
        ct.start()

__all__ = ['allClients','Client']

#-- 

客户端连接是:

import socket

HOST = '192.168.1.4'    # The remote host
PORT = 5000              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

data = s.recv(1024)
s.close()
print 'Received', data#repr(data)

需要快速解决方案.... 谢谢,

4 个答案:

答案 0 :(得分:0)

简短解决方案

sleep后添加简短connect

import time
time.sleep(3)

答案 1 :(得分:0)

等待回复:

with s.makefile('rb') as f:
     data = f.read() # block until the whole response is read
s.close()

您的代码中存在多个问题:

  • 嵌套while True不间断
  • finally: ..close()except ValueError: ..send
  • 之前执行
  • 多个self.sockfd.close()

此外,您应该使用.sendall()代替.send()

答案 2 :(得分:0)

您的服务器代码不包括客户端首先发送内容,

rm= self.sockfd.recv(1024)

但我的代码中没有看到任何内容

请尝试在客户端代码中发送内容

s.connect((HOST, PORT))
s.send("hello")

答案 3 :(得分:0)

我测试了你的代码,当我注释掉

rm= self.sockfd.recv(1024)
print rm

它工作正常。基本上服务器停在那里等待从未发过的消息。如果它仍然不适合你,可能会有两个问题。要么你有防火墙以某种方式阻止连接,要么你有旧的服务器在以前的尝试中运行,实际上没有被杀死。如果pythonw.exe或等效文件正在运行,请检查您的进程,如果它不应该,并将其终止。