简体   繁体   中英

Simple client program

server.py is fine and I use array to send data:

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

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.

from 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. See the Unix manual page recv(2) for the meaning of the optional argument flags; 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.

A good solution was suggested by @gnibbler.

Remember calling clientSocket.recv(1024) without saving it's return value it's like popping from a stack without saving the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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