0

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. I have a Python server running on my RPi, and a Java client running on my Windows laptop. 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". However this cannot be true, because my Java program receives data from the Pi! The Java program then closes due to the Pi server closing. But from what I've read online, Python's "error 32: broken pipe" is triggered when the remote socket closes prematurely!

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

Here is the code for my RPi server program:

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:

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:

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 MorseClient 192.168.1.101 42844
Connection made!
null
Connection closed by server

1 Answer 1

1

Good lord, why are you writing a server with sockets? Use Flask.

http://flask.pocoo.org/

Also, pretty sure s should not be sending all. 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)

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

3 Comments

Your answer does point out what the problem actually is. Very generic answers like the one you gave, and especially the part about using flask which is something very different and does not fit the intentions of the person asking, are not helpful for anybody.
Thank-you so much for that! Yes, the problem was that I was calling sendall on s and not client. (I'm not too sure what I was thinking...)
Actually @Klaus, I answered the question below my suggestion. And, as you can see the reply from the author, it was quite helpful. Also, pointing out a better approach can be quite helpful as well.

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.