Thursday, August 21, 2008

Socket in python

server:
#!/usr/bin/env python
import socket
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8001))
sock.listen(5)
while True:
connection,address = sock.accept()
try:
connection.settimeout(5)
buf = connection.recv(1024)
if buf == '1':
connection.send('this is one')
else:
connection.send('this is not one')
except socket.timeout:
print 'time out'
connection.close()

client:
#!/usr/bin/env python
def send():
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8001))
import time
time.sleep(1)
time.sleep(1)
sock.send('1')
print sock.recv(1024)
sock.close()

if __name__ == '__main__':
while(True):
send()

No comments: