问题描述
TCP Server 和 TCP Client 的 Java 程序如下。我已将必须读取的文件放在我的 Java 程序所在的同一文件夹中。现在,当我从 TCP 客户端输入文件名时,TCP 服务器将输出作为 找不到文件。我哪里错了?非常感谢您的帮助。
TCP 服务器
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class Tcpserver{
public static void main(String[] args)throws IOException{
ServerSocket ss = null;
Socket s = null;
try{
ss = new ServerSocket(3000);
}
catch(Exception e){
e.printstacktrace();
}
while(true){
try{
System.out.println("Server Ready....");
s = ss.accept();
System.out.println("Client Connected...");
InputStream istream = s.getInputStream();
Scanner fread = new Scanner(new
InputStreamReader(istream));
String fileName = fread.nextLine();
System.out.println("Reading contents of " + fileName);
Scanner contentRead = new Scanner(new
FileReader(fileName));
OutputStream ostream = s.getoutputStream();
PrintWriter pwrite = new PrintWriter(ostream,true);
while(contentRead.hasNext())
pwrite.println(contentRead.nextLine());
pwrite.close();
s.close();
}
catch(FileNotFoundException e){
OutputStream ostream = s.getoutputStream();
PrintWriter pwrite = new PrintWriter(ostream,true);
System.out.println("File Not Found");
pwrite.close();
}
}
}
}
TCP 客户端
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class TcpClient{
public static void main( String[] args ){
Socket s;
while(true){
try{
s = new Socket("127.0.0.1",3000);
OutputStream ostream = s.getoutputStream();
System.out.println("Enter filename");
Scanner input = new Scanner(system.in);
String fname = input.nextLine();
PrintWriter pwrite = new PrintWriter(ostream,true);
pwrite.println(fname);
InputStream istream = s.getInputStream();
Scanner cRead = new Scanner(new InputStreamReader(istream));
while(cRead.hasNext())
System.out.println(cRead.nextLine());
pwrite.close();
s.close();
}
catch(Exception e){
e.printstacktrace();
}
}
}
}
解决方法
我猜你在 Windows 系统上运行服务器/客户端应用程序。我认为这是一个与路径名相关的问题。因此,您可以使用双反斜杠传递文件名,如下例所示:
C:\\Documents and Settings\\user\\test.txt