gpt4 book ai didi

java - 客户端/服务器程序之间的通信停止(java)

转载 作者:行者123 更新时间:2023-12-01 22:04:53 25 4
gpt4 key购买 nike

我试图让客户端与java中的服务器进行通信,客户端只需发送想要搜索的文件的名称,服务器应该回答他的文件夹中是否存在。这是我写的代码。

客户端.java

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class client{
public static void main(String args[]) throws IOException, NumberFormatException, InterruptedException{
Socket client_socket = new Socket(args[0], Integer.parseInt(args[1]));
System.out.println("connected\n");


BufferedWriter netOut = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream(), "UTF-8"));
BufferedReader netIn = new BufferedReader(new InputStreamReader(client_socket.getInputStream(), "UTF-8"));

netOut.write(args[2]);
netOut.flush();

String exist = netIn.readLine();

System.out.println("The file you searched"+ exist);


client_socket.close();
}
}

args[0] 应该用作本地主机,args[1] 用作端口,args[2] 用作要搜索的文件的名称。

服务器.java

import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class server{
public static void main(String args[]) throws IOException, InterruptedException{

ServerSocket sock_server = new ServerSocket(Integer.parseInt(args[0]));

while(true){
Socket communication = sock_server.accept();
System.out.println("connected!\n");

BufferedWriter netOut = new BufferedWriter(new OutputStreamWriter(communication.getOutputStream(), "UTF-8"));
BufferedReader netIn = new BufferedReader(new InputStreamReader(communication.getInputStream(), "UTF-8"));

String fileName = new String();
fileName = netIn.readLine();

System.out.println("The name of the file is"+fileName);

File tempFile = new File(fileName);
boolean exists = tempFile.exists();
System.out.println(exists);
if(exists){
netOut.write("The file do exists");
netOut.flush();
} else {
netOut.write("The file doesn't exist");
netOut.flush();
}


communication.close();
}
}
}

arg[0] = 通信端口

发生的情况是服务器永远不会发送证明文件存在的字符串。我在服务器中添加了一些 println() 以确保从客户端到服务器的通信正常,并且看起来工作正常。

最佳答案

不知道为什么它在你的情况下不起作用,但你可以尝试在这种情况下使用ObjectInputStreamObjectOutputStream,我发现这非常有用。我测试了它并且可以很好地与您的代码配合使用。因此,在客户端,您可以使用以下内容:

...
ObjectOutputStream netOut = new ObjectOutputStream(client_socket.getOutputStream());
ObjectInputStream netIn = new ObjectInputStream(client_socket.getInputStream());
netOut.writeObject("a_file_name");
netOut.flush();
String exist = (String)netIn.readObject();

服务器端也类似:


ObjectOutputStream netOut = new ObjectOutputStream(communication.getOutputStream());
ObjectInputStream netIn = new ObjectInputStream(communication.getInputStream());
String fileName = new String();
fileName = (String)netIn.readObject();

if(exists){
netOut.writeObject("The file do exists");
netOut.flush();
} else {
netOut.writeObject("The file doesn't exist");
netOut.flush();
}

由于涉及转换,请确保您还捕获或声明 ClassNotFoundException

关于java - 客户端/服务器程序之间的通信停止(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58697373/

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