我正在尝试让客户端与Java中的服务器进行通信,客户端只是简单地发送要搜索的文件名,服务器应该回答文件夹中是否存在文件。 这是我写的代码。
client.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]用作要搜索的文件的名称。
server.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(),以确保从客户端到服务器的通信正常,并且似乎运行正常。