Question

I make server socket at Raspberry PI and client socket at Android mobile device. They can make connection each other and somehow there is an error at server socket side and the client side does not receive the message sent from the server side. My server side program is

import socket
import time
import picamera
import sys

# Start a socket listening for connections on 192.168.0.17:8080
server_socket = socket.socket()
server_socket.bind(('192.168.0.17', 8080))
server_socket.listen(0)
print >> sys.stderr,'Listening'
# Accept a single connection and make a file-like object out of it
while True:
   connection = server_socket.accept()[0].makefile('wb')
   print >> sys.stderr, 'Connected with'
   try:
      print >> sys.stderr, 'going to write'
      connection.write("linked")
      connection.flush()
      print >> sys.stderr, 'Sent message'
      time.sleep(20)
   finally:
      print >> sys.stderr, 'Server socket is going to be closed'
      connection.close()
      server_socket.close()
      print >> sys.stderr, 'Server socket is closed'

The print output shows that the server socket sent message, it is as follow

Listening
Connected with
going to write
Sent message
Server socket is going to be closed
Server socket is closed

The error is

Traceback (most recent call last):
  File "/home/pi/PY_programs/camera_play.py", line 13, in <module>
    connection = server_socket.accept()[0].makefile('wb')
  File "/usr/lib/python2.7/socket.py", line 202, in accept
    sock, addr = self._sock.accept()
  File "/usr/lib/python2.7/socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor

What is wrong with this error and why I don't receive 'linked' message at the client. Thanks

Was it helpful?

Solution

finally:
      print >> sys.stderr, 'Server socket is going to be closed'
      connection.close()
      server_socket.close()
      print >> sys.stderr, 'Server socket is closed'

Here you close the server socket too. Don't do that, you need your server_socket on the next iteration of your loop so it can accept a new client.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top