1

Why does my connection stop after 3 print statements if I have the conn.send() line? If that line is commented out, the connection stays open indefinitely. It is hitting the exception for some reason, but I don't know why and I am inexperienced with python.

server.py:

import random
import signal
import socket
import struct
import sys
import time

PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', PORT))
s.listen(1)
print("Server started on port %u" % PORT)

try:
    while True:
        (conn, addr) = s.accept()
        conn.setblocking(0)
        print("Client connected: %s:%d" % addr)
        while True:
            print "hey"
            conn.send("random")
            time.sleep(1)
except:
    s.close()
    print "exception"

client.py:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 1234                 # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close
Adam Johns
  • 35,397
  • 25
  • 123
  • 176

1 Answers1

0

The reason for this behavior is the socket is actually closed after the clients first recv(), your server just doesn't realize it until the third attempt at send(). Calling close() in your client didn't change anything because previously the program was terminating which closed the socket anyway. This thread explains why this is very likely what's happening. To test this theory, you could try having the client sleep (or select) and print more recv() calls, before closing the socket.

Community
  • 1
  • 1
ErlVolton
  • 6,714
  • 2
  • 15
  • 26