【问题标题】:Making a TCP server and client socket connection between Raspberry PI and Android Device在 Raspberry PI 和 Android 设备之间建立 TCP 服务器和客户端套接字连接
【发布时间】:2014-06-22 19:15:09
【问题描述】:

我在 Raspberry PI 上制作服务器套接字,在 Android 移动设备上制作客户端套接字。 他们可以相互建立连接,并且服务器套接字端出现错误,客户端没有收到服务器端发送的消息。 我的服务器端程序是

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'

打印输出显示服务器socket发送了消息,如下

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

错误是

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

此错误有什么问题以及为什么我没有在客户端收到“链接”消息。 谢谢

【问题讨论】:

    标签: networking tcp sockets


    【解决方案1】:
    finally:
          print >> sys.stderr, 'Server socket is going to be closed'
          connection.close()
          server_socket.close()
          print >> sys.stderr, 'Server socket is closed'
    

    在这里你也关闭了服务器套接字。不要那样做,您需要在循环的下一次迭代中使用 server_socket,以便它可以接受新客户端。

    【讨论】:

    • 谢谢,但无论如何我需要关闭套接字,对吗?您的意思是从客户端关闭套接字。现在我正在接收数据。
    • @batuman 服务器套接字用于接受新连接。您的 connection 变量是代表与客户端连接的变量 - 您已经关闭了该变量。如果您的客户端没有收到您在此处发送的字符串,则可能是客户端代码有问题。
    猜你喜欢
    • 2017-03-16
    • 2012-04-24
    • 2015-01-19
    • 2011-05-20
    • 2021-11-06
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多