I am doing an simple Python socket server and client that need to be able to receive few inputs and not losing connection. I can input one command but after receiving the reply the connection is lost. How can i keep it alive?
Client code
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except sockets.error , msg:
print 'Failed to create socket, Error code:' + str(msg[0]) + ' , Error message :' + msg[1]
sys.exit()
print 'Socket Created'
host = '127.0.0.1'
port = 8888
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = raw_input('Sladu inn skipun :')
try :
s.sendall(message)
except socket.error:
print 'Send failed'
sys.exit()
print 'Message send successfully'
reply = s.recv(4096)
print reply
s.close()
Server code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
from thread import *
import glob
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
def clientthread(conn):
while True:
data = conn.recv(1024)
if data == "show dir":
reply = glob.glob('*.*')
else:
reply ="Þessi skipun hefur ekki verið forrituð"
if not data:
break
conn.send(str(reply))
while 1:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
elseon awhileloop, and it's very useful. (Well, more often useful withforthanwhile, but thenforis more often useful thanforanyway…) It's explained in the tutorial, but basically, it lets you usebreakwithout needing thefound = Trueflag or other out-of-band way of distinguishing "broke out early because of success" vs. "finished the loop because we never found anything" that's so common in C.