gpt4 book ai didi

java - 一个简单的java客户端服务器程序

转载 作者:行者123 更新时间:2023-11-29 07:59:01 25 4
gpt4 key购买 nike

所以我为我的大学迷你项目用 Java 编写了这个客户端服务器程序。请注意,这只是我正在进行的一个大项目的一个小模块。我需要一个字符串从客户端发送到服务器。服务器将返回给客户端的字符串。 (稍后将修改代码,以便在发送回之前处理字符串)。客户端将在需要时向服务器发送一个字符串。因此,这意味着服务器必须无限期运行。

我在这里面临的问题是,我的服务器仅在客户端第一次发送字符串时才能完美运行。如果我第二次使用不同的字符串运行客户端,我将返回之前发送到服务器的相同字符串!

这是我的服务器程序:

        public class Server {

public static boolean x = true;
public static String reply;

public static void main(String a[]) throws Exception {

System.out.println("Entered server console..");
Socket echoSocket = null;
ServerSocket serverSocket = null;
PrintWriter out = null;
BufferedReader in = null;

System.out.println("Initializing Connection..");

boolean runFlag = true;
try {
serverSocket = new ServerSocket(77);

while (runFlag) {
echoSocket = serverSocket.accept();

out = new PrintWriter(echoSocket.getOutputStream(), true);

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

while (x) {

in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
reply = in.readLine();
if (reply != null) {
x = false;
}
}
System.out.println("received: " + reply);

out.println(reply);

System.out.println("sent back: " + reply);
stdIn.close();
}

} catch (Exception e) {
System.out.println("Exception in starting server: " + e.getMessage());
} finally {
out.close();
in.close();
echoSocket.close();
}

}
}

这是我的客户端程序:

    public class Client {
public static String reply,temp;
public static boolean x=true;

public Client()
{
temp="lala";
}
public Client(String t)
{
temp=t;
}

public static void main(String[] args) throws IOException {

Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;

try {
echoSocket = new Socket("localhost", 77);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

temp="lala"; //this is the string to be sent

out.println(temp);

while (x) {
reply= in.readLine();
if(reply!=null)
{
x=false;
}
}

System.out.println("reply: "+reply);

out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}

谁能帮我找出问题所在?

最佳答案

while (x) {
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
reply = in.readLine();
if (reply != null) {
x = false;
}
}

您的服务器在客户端第一次连接时进入此循环,并将回复字符串设置为来自客户端的一些输入。但是,它再也不会进入此循环,因为 x 的值永远不会变回 true。

关于java - 一个简单的java客户端服务器程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15653074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com