[Tutor] A very simple socket server question

Kent Johnson kent37 at tds.net
Tue Mar 29 22:55:10 CEST 2005


Kevin wrote:
> I figured out how to create a very simple socket server. Though this
> socket server does exactly nothing special. I can however get it to
> send only one line of data back to the telnet client.

You need two nested loops - an outer loop to accept the connection and an inner loop to proces the 
data. The way you have it now, it processes one line, then blocks waiting for a new connection.

Take a look at example 19-1 in Python in a Nutshell. You can download it here:
http://examples.oreilly.com/pythonian/

You might also be interested in example 19-5 which does the same thing using the SocketServer module 
and example 19-9 which uses Twisted.

Kent

> 
> import socket
> ######################
> HOST = ""
> PORT = 4000
> ######################
> 
> s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
> s.bind((HOST,PORT))
> s.listen(5)
> def log():
> 	a = addr
> 	b = str(a)
> 	logfile = open("logfile.log", "a+")
> 	logfile.write("Attempting connection from "+b+"\n")
> 	logfile.close()
> 
> while 1:
> 	conn, addr = s.accept()
> 	data = conn.recv(1024)
>         if not data:
>               break
>         else:
>               conn.send(data)
> 
> How can I make it so that when a client sends the word hello the
> server will write back
> hello, how are you?.
> 
> Thanks
> Kevin
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list