我有一个服务器和client.java,它可以通过输入和输出流双向发送和接受消息,但是一旦有连接,就会发送一条消息,然后服务器关闭它自己,到目前为止,我已经放置了缓冲阅读器等等。在一个 finally 块中,该块仅在 e == true 时激活(e 表示退出,因此我可以在需要时停止它)但在发送/接收消息后它仍然停止构建第一个问题如何阻止它关闭它自己?第二个问题如何将输入流阅读器放入循环中以不断测试来自 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
}
服务器.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();
}
}