Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

Java can't get a continuous reading/writing to a socket

I'm studying electronic engineering but for my internship I've been asked to make a program that must communicate via a socket to a certain ip and port. The program has a main class which is the GUI and I made another class for the connection which runs parallel using a Thread. The problem is that when I click the "Connect" button that I have on my GUI, it only receives or sends once the data, despite having a while loop. To further receive and send data I must spam-click my connect and disconnect button.

public class ConnectionSocket implements Runnable {

    private final int port;
    private final String ipAddr;
    private final Observer observador;
    
    private DataInputStream in;
    private DataOutputStream out;
    private Socket sc = null;
    
    private boolean inputAvailable = false;
    public boolean lastInput = false;
    private String nextOutputMessage;
    private boolean disconnect=false;
    private Observable observable;
    
    
    public ConnectionSocket(String ip, int p , Observer panel) {
        this.ipAddr = ip;
        this.port = p;
        this.observador = panel;
    }
    
    @Override
    public void run() {
 
        this.observable = new Observable();
        observable.addPropertyChangeListener(observador);
        this.observable.notifyData("Message Connected");
        System.out.print("
**********************
Conectado
**********************
");
        
        while (!disconnect) {
            
            try {
                try {
                    sc = new Socket(this.ipAddr , this.port);
                }
                catch (IOException e) {
                    System.out.println("Socket TimeOut");
                }
                if(sc != null) {
                    out = new DataOutputStream(sc.getOutputStream());
                    in = new DataInputStream(sc.getInputStream());
                }
                
                
                while(!disconnect){
                
                    if (sc != null) {

                        try {
                            if(in.available() != 0) {
                                receiveData();
                            }
                            else {
                                inputAvailable = false;
                            }
                        }
                        catch(IOException ex) {
                            System.out.println("***Read or write error***");
                            System.out.println(ex.toString());
                        }
                    }
                }
                
                if ( sc != null ) {
                try { sc.close(); }
                catch ( IOException e ) {} 
            }
            } catch (IOException ex) {
                Logger.getLogger(ConnectionSocket.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //Close the socket
        cutConnection();
        System.out.print("
**********************
Desconectado
**********************
");
 
    }
    
    public void sendNewData(String msg) throws IOException {   //this method receives data from the GUI//
        nextOutputMessage = msg;
        sendData();
    }
    
    
    private synchronized void sendData() throws IOException { 
        
        System.out.println("Panel: " + nextOutputMessage);
        out.writeByte((byte) Integer.parseInt(nextOutputMessage));
    }
    
    private synchronized void receiveData() throws IOException {
        
        if(!inputAvailable)System.out.print("CUBE: ");
        inputAvailable = true;
        while(in.available() != 0) {
            byte dat = (byte) in.read();
            this.observable.notifyData(Character.toString((char) dat));
            System.out.print((char) dat);
        }
    }

    public void cutConnection() {
        try {
            disconnect = true;
            if(this.in != null) {
                this.in.close();
            }
            if(this.out != null) {
                this.out.close();
            }
            if(this.sc != null) {
                this.sc.close();
            }
        } catch (IOException ex) {
            this.sc = null;
        }
    }

}

I use two additional classes which use PropertyChangeListener to send the data received to the GUI, otherwise it just blocks it. I receive and send data as ASCII code.

This is the method in the GUI class which starts the thread (the connection)

private void connect(String ip, int port) {

        jButton_connect.setText("Desconectar");
        labelMessage("Conectando...");
        observerPanel = new Observer(this);
        connection = new ConnectionSocket(ip , port, observerPanel);
        Thread t = new Thread(connection);
        t.start();
}

So basically I would appreciate any hint about what I'm doing wrong, because I can't really find any solution suitable for my needs. BTW any solution that includes getting rid of the double while loop would be great, as it consumes a lot of cpu in that point. Feel free to criticise any stupid thing I made because I had to learn java from zero to do this so it's probably not really good. Thanks in advance

Edit 1: Does the sc = new Socket(this.ipAddr , this.port); sentence need to be called in the loop or once it's called it permanently bounds to that ip and port? I only need to connect to a specific ip and port. Thanks

question from:https://stackoverflow.com/questions/66061978/java-cant-get-a-continuous-reading-writing-to-a-socket

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...