简体   繁体   中英

Python Problem With sockets

Hy, i'm try to create a simple Telnet Server in python, but the server receve just one command send by Client... Code:

from socket import *

server = socket(AF_INET, SOCK_STREAM)
server.bind((gethostname(), 23))
server.listen(5)

while 1:
   (connection, address) = server.accept()
   data = connection.recv(1024)
   print data
   if data=='X':
     break 

connection.close()

Taking the server.accept outside the while loop will allow your client to send in more commands:

from socket import *

server = socket(AF_INET, SOCK_STREAM)
server.bind((gethostname(), 23))
server.listen(5)

(connection, address) = server.accept()
while 1:
    data = connection.recv(1024)
    print data
    if data=='X':
        break 

connection.close()

There are a couple more problems with this: your server will only allow one client. As long as that one client is connected, no other client can connect. You can solve this by using threads (which can be tricky to get right), or using the select module.

And telnet sends newlines, so data will never be 'X'. You can check with if data.strip() == 'X':

Also, if your client disconnects, data will be an empty string. So you may want to add the additional check too:

if not data:
    break

After receiving a bunch of data you print it out and then accept a new client. So the old client's socket is not used anymore.

Once you read data into data variable, you print it then, if data is different from 'X', connection goes out of scope and it is closed.

You need to store that connection somewhere and close it when you really need to (I guess when client sends in 'exit'...).

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