0

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()
asked Dec 29, 2010 at 11:44

3 Answers 3

2

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
answered Dec 29, 2010 at 12:00
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Dec 29, 2010 at 11:49

Comments

0

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

answered Dec 29, 2010 at 11:48

1 Comment

yes, but if the Client send "aaa" the Server get the message and print it and the server dont close the connection!! after the client send "www" the Server dont print any message!! but the connection remains active!!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.