创建一个使用套接字连接的应用程序,允许客户端指定文本文件的文件名,并让服务器发送文件的内容或指示文件不存在。服务器必须包含基于文本的密码文件(“用户名”和“密码”)。客户端必须传递有效的用户名和密码才能与服务器建立连接。
注意:更好的方法是加密密码文件。 Java 加密扩展提供了一个 API。
如何在没有语法错误的情况下实现它?我会有一个 Client.java 和一个 Server.java。我需要测试文件才能运行吗?
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket sersock=new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock=sersock.accept(); // binding with port 4000
System.out.println("Connection is successful and waiting for chatting");
InputStream istream=sock.getInputStream();
BufferedReader fileRead=new BufferedReader(new InputStreamReader (istream));
String fname=fileRead.readLine();
BufferedReader contentRead=new BufferedReader(new FileReader(fname));
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream, true);
String str;
while((str=contentRead.readLine()) != null)
{
pwrite.println(str);
}
sock.close();
pwrite.close();
fileRead.close();
contentRead.close();
}
} // end class
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket sock=new Socket("127.0.0.1", 4000);
System.out.print("Enter the file name: ");
BufferedReader keyRead=new BufferedReader(new InputStreamReader (System.in));
String fname=keyRead.readLine();
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream, true);
pwrite.println(fname);
InputStream istream=sock.getInputStream();
BufferedReader socketRead=new BufferedReader(new InputStreamReader (istream));
String str;
while((str=socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
}
pwrite.close();
socketRead.close();
keyRead.close();
}
} // end class
缺少用户名和密码
需要纠正什么?