Interactive socket connection
Rayed Al-Rashed
rayed at saudi.net.sa
Sun Jun 2 00:42:44 EDT 2002
Thanks for the response, flush() helped a little, but I faced another
problem, waiting for input. I built another version it work great using
"select" module to poll both the socket and stdin.
The finished program is a POP proxy that accept the connection from the
user and depending on the user name it forward the connection to the proper
POP3 server (configured by getuserserver function):
for example user "rayed" go to server "r.pop.mydomain.com"
Thanks a lot for your advice, any ideas on how to improve it? :)
------------------------------------
#!/usr/local/bin/python
import sys
import string
import socket
import select
def getuserserver(user):
server = "%s.pop.mydomain.com" % (user[0], )
return (user, server)
print "+OK POP3 server ready"
sys.stdout.flush()
# GET USER NAME
while 1:
s = sys.stdin.readline()
s = string.strip(s)
s = string.lower(s)
try:
(command, username) = string.split(s, " ", 2)
except:
command = s
if command == "user":
break
elif command == "quit":
print "+OK Sayonara"
sys.exit()
else:
print "-ERR Unknown AUTHORIZATION state command"
sys.stdout.flush()
(id,server) = getuserserver(username)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((server, 110))
buf = s.recv(8000)
s.send("USER %s\r\n" % (id,))
while 1:
r,w,e = select.select ([sys.stdin,s], [], [sys.stdin,s])
if s in r:
buf = s.recv(8000)
if not buf:
# Connection closed
break
sys.stdout.write(buf)
sys.stdout.flush()
if sys.stdin in r:
buf = sys.stdin.readline()
s.send(buf)
------------------------------------
Peter Hansen wrote:
> Rayed Al-Rashed wrote:
>
>>Hello,
>>
>>I am trying to build POP3 proxy, I want it to run from "inetd" so it should
>>communicate with the user using regular stdin, stdout.
>>I built a small code that should run as general proxy for any protocol, but
>>I faced the following problem, it doesn't show any output from the server
>>until I pass it a command [...]
>
>
> Are you maybe in need of a sys.stdout.flush() to get the output to
> be sent after the sys.stdout.write()?
>
> -Peter
More information about the Python-list
mailing list