简体   繁体   English

简单的客户端程序

[英]Simple client program

server.py is fine and I use array to send data: server.py很好,我使用数组发送数据:

for i in range(0,len(outputdata)):       
    connectionSocket.send(outputdata[i])
    connectionSocket.close()

But my client don't work(print nothing): 但是我的客户不工作(什么都不打印):

#import socket module
from socket import *

serverName = '127.0.0.1'    
serverPort = 9999    
clientSocket = socket(AF_INET,SOCK_STREAM)    
clientSocket.connect((serverName,serverPort))    
request = raw_input('Input the filename:')   
clientSocket.send(request)    
while (clientSocket.recv(1024)):
    print clientSocket.recv(1024)
clientSocket.close()

Why doesn't this work? 为什么不起作用?

The first clientSocket.recv(1024) is throwing away those bytes 第一个clientSocket.recv(1024)丢弃这些字节

while (clientSocket.recv(1024)):
    print clientSocket.recv(1024)

You need to save them into a variable like this 您需要将它们保存到这样的变量中

while True:
    data = clientSocket.recv(1024)
    if not data:
        break
    print data

The command clientSocket.recv(1024) is a command that will fetch available data. 命令clientSocket.recv(1024)是将获取可用数据的命令。

from Python Docs: 从Python Docs:

Receive data from the socket. 从套接字接收数据。 The return value is a string representing the data received. 返回值是代表接收到的数据的字符串。 The maximum amount of data to be received at once is specified by bufsize. 一次接收的最大数据量由bufsize指定。 See the Unix manual page recv(2) for the meaning of the optional argument flags; 有关可选参数标志的含义,请参见Unix手册页recv(2)。 it defaults to zero. 它默认为零。

To understand it better, your server is sending some data, the client receives that data and holds it in a buffer, the command will go to that buffer and pop the data (with max of 1024 at your code) so if you have 1024 bytes waiting in the buffer the first recv(1024) command will get all the data in the buffer and the second recv(1024) will be empty. 为了更好地理解它,您的服务器正在发送一些数据,客户端接收到该数据并将其保存在缓冲区中,该命令将转到该缓冲区并弹出数据(您的代码中最大为1024),因此如果您有1024字节在缓冲区中等待时,第一个recv(1024)命令将获取缓冲区中的所有数据,第二个recv(1024)将为空。

A good solution was suggested by @gnibbler. @gnibbler建议一个好的解决方案。

Remember calling clientSocket.recv(1024) without saving it's return value it's like popping from a stack without saving the value. 记住在不保存返回值的情况下调用clientSocket.recv(1024)就像从堆栈中弹出而不保存该值一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM