简体   繁体   中英

Java loop to check for inputstream reader

I have a server and client.java which can send and accept a message both ways via input and output stream but as soon as there is a connection a message is sent and then the server closes its self, so far I have put the buffered reader ect. in a finally block which is only activated when e == true (e for exit so I can stop it when I want) but it still stops the build after sending/receiving a message 1st question how can I stop it from closing its self? 2nd question how can I put input stream reader in a loop to continually test for input from client.java?

Client.java

package client;

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

    // Variables declaration - do not modify                     
/**
 *
 * @author ****
 */
public class Client extends javax.swing.JFrame {

;

    public Client() {
        initComponents();
    }
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    jTextField1.setText("");
    input = jTextField1.getText();
    send(input);     
    }                                           
    int port = 1234;
    String hostname = "localhost";
    String input,output;

    public void send(String text) {   
    try {
         Socket skt = new Socket(hostname, port);           /*Connects to server*/

         BufferedReader in = new BufferedReader(new
         InputStreamReader(skt.getInputStream()));          /*Reads from server*/
         System.out.println("Server:" + in.readLine());

         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
         out.println(text);                                   /*Writes to server*/
         out.close();    /*Closes all*/
         in.close();
         skt.close();

      }
      catch(Exception e) {
         System.out.print("Error Connecting to Server\n");
      } 
    }
    public void startUP() {

    }
    public static void main(String args[]) {
     Client c = new Client();
     c.startUP();
     c.send("Server is online");
      new Client().setVisible(true);

   }


    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

Server.java

package server;

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

class Server {
    /*
     To send string to client use "out.print(data)"
     To use info sent from client use "in.readLine()"
     */
        int port = 1234;
    String input,output;
    boolean e = false;
    String question = "how are you";
    String answer = "i am fine";

    public void send(String text) {
        ServerSocket srvr = null;
        Socket skt = null;
         PrintWriter out = null;
         BufferedReader in = null;
    try {
         srvr = new ServerSocket(port);
         skt = srvr.accept();                       /*Waiting for Connection from client*/
         System.out.println("Connection = true");

         out = new PrintWriter(skt.getOutputStream(), true);
         out.println(text);                                                  /*Write/Send to Client*/

         in = new BufferedReader(new
         InputStreamReader(skt.getInputStream()));                   /*Read from Client*/
         System.out.println("Client:" + in.readLine());
         input = in.readLine();

      } catch( Exception e) {
         System.out.println("Error Connecting\n");
      } finally {
        if(e == true){
        try {
         out.close();
         in.close();
         skt.close();               /*Closes all*/
         srvr.close();

         } catch (IOException e) {
        }
    }
    }
    }

public void testFor() {
    if(input.equals(question)){ send(answer); }
}

   public static void main(String args[]) {
       Server s = new Server();

       s.send("Client is online");  //sends a message to client
      // s.testFor();

   }
}

ok well to start of, to stop a while loop, at some point you have to say that statement is false or true (depending what u use in first place). so ie if you say while(true) . this will always be true as there is nothing to compare to therefore it will create infinite loop going on forever. however if you say we do something like that

 `while(x=true)'
  {
     x=false;
  }

this will ensure that you stop the while loop and you will not enter it again. How? well we enter the while loop under conditon that x is true. as soon as we enter that loop we declare x to be false. therefore on next iteration x will be false and as a result we will not enter while loop. Kinda straight forward isn't it ?
As of the problem it self, i suggest reading THIS article. It is very clear and nicely laid out and it will show you how to write good socket based program:)

1st question is to call the bufferreader, printwriter etc.. out of the methods then use the .close in a separate method which could be activated at any time.

for my 2nd question I found I can use a while loop:

    while(true) {
//code...
    }

Thanks for no one's help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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