0

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

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but anyway I need to close the socket, right? You mean to close the socket from the client side. Now I am receiving data.
@batuman The server socket is there to accept new connections. Your connection variable is the one representing the connection to the client - and you already do close that one. If your client doesn't receive the string you send here, it's probably a problem in the client code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.