I am having trouble with my server and client. I need the client to send information to the server, the server sends the information back, and the process repeats once more. I was able to get the client to connect to the server and have infomation sent the first round but I cant seem to figure out how to get the server to listen to client again after I shutdown the sending side using the function conn.shutdown(1). I tried connecting to the port again but I get an error that says "Transport endpoint is already connected". Any suggestions?
-
possible duplicate of How can I reconnect a socket after a broken pipe?Nir Alfasi– Nir Alfasi2015年02月04日 04:34:13 +00:00Commented Feb 4, 2015 at 4:34
-
1Why bother shutting down until the connection is done? By default a just-closed socket will stay in a "in use" state for a while in case of stray packets -- this can be worked around but it's unadvisable except in the rare cases in which it's indispensable, and yours doesn't seem to be as you can just avoid shutting down prematurely, no?Alex Martelli– Alex Martelli2015年02月04日 04:43:08 +00:00Commented Feb 4, 2015 at 4:43
1 Answer 1
Try to use threads(Multithreading)-
Server App
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
def clientthread(conn):
conn.send('connected')
try:
while True:
data = conn.recv(1024)
processData(conn,data)
if not data:
break
except Exception as ex:
print ex
conn.close()
while True:
conn, addr = s.accept()
print 'Got connection from', addr
thread.start_new_thread(clientthread ,(conn,))
s.close()
Client App
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done