0

The following script receiving data from a socket connection does not react to the CTRL+C signal sent in order to exit:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
"""
import socket
HOST = '192.168.178.1'
PORT = 1012
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while 1:
    data = s.recv(1024)
    print 'Received', repr(data)
s.close()

How can the program be modified so that program input or the default signal causes the infinite loop to be broken in order to end the program gracefully?

miken32
  • 42,008
  • 16
  • 111
  • 154
none
  • 275
  • 2
  • 4
  • 10
  • For a similar problem in server situation see http://stackoverflow.com/questions/1148062/python-socket-accept-blocks-prevents-app-from-quitting – none Feb 19 '11 at 17:53

2 Answers2

0

Use Select

import socket
import select

HOST = '192.168.178.1'
PORT = 1012
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(1)
s.connect((HOST, PORT))
time_out=None
ready=[[s],[],[], time_out]

if ready:
   s.recv(1024)

s.close()
anijhaw
  • 8,954
  • 7
  • 35
  • 36
  • Your example exits once something has been received. My intention is to contiuously receive and only exit on user input (CTRL+C signal). Thank you anyway! – none Feb 19 '11 at 21:41
0

One solution is to close the socket from another thread as shown by S. Prasanna in his blog article. Another may be to catch the signal somehow.

none
  • 275
  • 2
  • 4
  • 10