简体   繁体   English

无法将任何内容从Python服务器发送到Java客户端

[英]Unable to send anything from Python server to Java client

I've set up a Raspberry Pi 3 and I want to make a program that sends data whenever a button is pushed on my breadboard. 我已经设置了Raspberry Pi 3,并且想要创建一个程序,只要在面包板上按一下按钮就可以发送数据。 I have a Python server running on my RPi, and a Java client running on my Windows laptop. 我在RPi上运行一个Python服务器,在Windows笔记本电脑上运行一个Java客户端。 However, whenever I send data to my Java client, it receives the data, and then for some reason, the RPi server closes the program due to "broken pipe". 但是,每当我向Java客户端发送数据时,它都会接收数据,然后由于某种原因,RPi服务器会由于“管道中断”而关闭程序。 However this cannot be true, because my Java program receives data from the Pi! 但是,这不可能成立,因为我的Java程序从Pi接收数据! The Java program then closes due to the Pi server closing. 然后,由于Pi服务器关闭,Java程序关闭。 But from what I've read online, Python's "error 32: broken pipe" is triggered when the remote socket closes prematurely! 但是从我在线阅读的内容来看,远程套接字过早关闭时会触发Python的“错误32:管道损坏”!

What's going on here? 这里发生了什么? Why can't I keep my server running? 为什么我不能保持服务器运行?

(PS: The data that my Java program receives is wrong, but it receives data nonetheless. I send "1\\n", and I receive null .) (PS:我的Java程序接收到的数据是错误的,但是仍然接收到数据。我发送“ 1 \\ n”,而我接收到null 。)

Here is the code for my RPi server program: 这是我的RPi服务器程序的代码:

import RPi.GPIO as GPIO
from time import sleep
import atexit
import socket
import sys

GPIO.setmode(GPIO.BOARD)
GPIO.setup(5, GPIO.IN)
GPIO.setup(7, GPIO.OUT)


def cleanup():
    print("Goodbye.")
    s.close()
    GPIO.cleanup()
atexit.register(cleanup)

THRESHOLD= 0.3

host= sys.argv[1]
port= 42844

length= 0

def displayDot():
    GPIO.output(7,True)
    sleep(0.2)
    GPIO.output(7,False)
def displayDash():
    GPIO.output(7,True)
    sleep(0.5)
    GPIO.output(7,False)

try:
    print("Initializing connection...")
    s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    serverAddress= (host, 42844)
    s.bind(serverAddress)
    print("Connection initialized!")

    print("Waiting for client...")
    s.listen(1) #Puts the server socket into server mode
    client, address= s.accept()
    print(address)
    while True:
        if not GPIO.input(5):
            length+= 0.1
            GPIO.output(7,True)
            s.sendall('1\n')
            print("HELLO??")
        else:
            if length!=0:
                if length>=THRESHOLD:
                    print("Dash") #displayDash()
                else:
                    print("Dot") #displayDot()
                s.sendall('0')
                length= 0
                GPIO.output(7,False)
except KeyboardInterrupt:
    print("\nScript Exited.")
    cleanup();

Here's the code for the Java client program: 这是Java客户端程序的代码:

import java.net.*;
import java.io.*;

public class MorseClient{
  public static void main(String[] args) throws IOException{
String hostname= null; //Initialize
int portNumber= 0; //Initialize
try {
  hostname= args[0];
  portNumber= Integer.parseInt(args[1]);
}
catch(ArrayIndexOutOfBoundsException aiobe) {
  System.err.println("ERROR. Please specify server address, and port number, respectively");
  System.exit(1);
}

    Socket redoSocket;

    long initTime;

    try(
      Socket echoSocket= new Socket(hostname, portNumber);

      PrintWriter out= new PrintWriter(echoSocket.getOutputStream(), true);

      BufferedReader in= new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

      BufferedReader stdin= new BufferedReader(new InputStreamReader(System.in));
      ){
        redoSocket= echoSocket;
        System.out.println("Connection made!");

        String userInput= "";

        //Order of priority
        //Connection time= 0
        //Latency= 0
        //Bandwidth= 1
        redoSocket.setPerformancePreferences(0,0,1);

        //Optimizes reliability
        redoSocket.setTrafficClass(0x04);

        echoSocket.setKeepAlive(true);

        String returned= "";
        while(true){
          returned= in.readLine();

          System.out.println(returned);
          if(!(returned.isEmpty())){
            System.out.println(returned);
            System.out.println("YEP");
          }
          System.out.println(returned);
          if(returned==null){
            System.out.println("HAHA");
            System.out.println("Attempting to reconnect...");
            redoSocket= new Socket(hostname,portNumber);
            System.out.println(redoSocket.isConnected());
          }
        }
      }
      catch(Exception e){
        if(e instanceof ConnectException || e instanceof SocketException || e instanceof NullPointerException)
          System.err.println("Connection closed by server");
        else
          System.err.println(e.toString());
      }
  }
}

The output for the Pi server is: Pi服务器的输出为:

python ServerMorse.py 192.168.1.101
Initializing connection...
Connection initialized!
Waiting for client...
('192.168.1.14', 58067)
('192.168.1.14', 58067)
Traceback (most recent call last):
  File "ServerMorse.py", in <module>
    s.sendall('1\n')
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
Goodbye.

And the output for the Java client: 以及Java客户端的输出:

java MorseClient 192.168.1.101 42844
Connection made!
null
Connection closed by server

Good lord, why are you writing a server with sockets? 上帝,您为什么要编写带有套接字的服务器? Use Flask. 使用烧瓶。

http://flask.pocoo.org/ http://flask.pocoo.org/

Also, pretty sure s should not be sending all. 另外,很确定s不应发送全部。 It should be like this: 应该是这样的:

conn, addr = server.accept()
conn.sendall(....     # <- this is what sends

Here is some sample code from a server I wrote with sockets once..might be useful: 这是我曾经用套接字编写的服务器中的一些示例代码。可能很有用:

def server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
    address = ('127.0.0.1', 5020)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(address)
    server.listen(1)
    conn, addr = server.accept()
    ...
    ...
    conn.sendall(response_ok(some_stuff))
    ...
    conn.close()

(response_ok is a function I wrote) (response_ok是我编写的函数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM