The Psicopath
The Psicopath

Reputation: 75

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()

Upvotes: 0

Views: 179

Answers (3)

Mew
Mew

Reputation: 1049

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

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318778

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.

Upvotes: 1

Simone
Simone

Reputation: 11797

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'...).

Upvotes: 0

Related Questions