简体   繁体   English

Java循环检查输入流阅读器

[英]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. 我有一个服务器和client.java,它们可以通过输入和输出流同时发送和接受消息,但是一旦建立连接,就发送了一条消息,然后服务器关闭了自身,到目前为止,我已经将缓冲的读取器放入等等。 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? 在finally块中,该块仅在e == true时才激活(e表示退出,因此我可以在需要时停止它),但是在发送/接收消息后它仍然停止构建第一个问题我如何才能阻止它关闭自身? 2nd question how can I put input stream reader in a loop to continually test for input from client.java? 第二个问题,如何将输入流阅读器放入循环中,以不断测试来自client.java的输入?

Client.java 客户端.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 服务器.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). 好的开始,要停止一个while循环,在某些时候您必须说该语句是false还是true(取决于您首先使用的是什么)。 so ie if you say while(true) . 所以,如果你说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. 这将确保您停止while循环,并且不会再次输入它。 How? 怎么样? well we enter the while loop under conditon that x is true. 好吧,我们在x为真的条件下进入while循环。 as soon as we enter that loop we declare x to be false. 进入该循环后,我们便宣布x为假。 therefore on next iteration x will be false and as a result we will not enter while loop. 因此,在下一次迭代中,x将为false,结果我们将不会进入while循环。 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. 第一个问题是从方法中调用bufferreader,printwriter等。然后在单独的方法中使用.close,该方法可以随时激活。

for my 2nd question I found I can use a while loop: 对于第二个问题,我发现可以使用while循环:

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

Thanks for no one's help. 谢谢没有人的帮助。

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

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