客户端 - 服务器(从服务器到客户端的文件传输)
问题描述:
这是一个文件传输程序。客户端发送文件名,然后如果该文件存在,则服务器将文件发送给客户端。当文件不存在时,我希望服务器发送“文件不存在”之类的消息。客户端 - 服务器(从服务器到客户端的文件传输)
public static void main(String[] args) {
Socket socket = null;
String server = "localhost";
DataInputStream in;
BufferedReader input;
PrintWriter output;
int port = 1500;
File file;
file = new File("G:\\o.txt");
try{
if(!file.exists())
file.createNewFile();
}
catch(Exception e){
System.out.println("error1");
}
try {
socket = new Socket(server, port);
System.out.println("Connected To Server With This Ip" + socket.getInetAddress() + " On This Port :" + socket.getPort());
}
catch (UnknownHostException e) {
System.out.println(e);
}
catch (IOException e) {
System.out.println(e);
}
try {
output = new PrintWriter(socket.getOutputStream(),true);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String filewanted="H:\\\\o.txt";
output.println(filewanted);
in=new DataInputStream(socket.getInputStream());
int flag=0;
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
int b=in.readInt();
for(int i=1;i<=b;i++)
{
String message= input.readLine();
bw.write(message);
bw.newLine();
flag++;
}
bw.close();
if(flag!=0){
System.out.println("File Was Transferd Successfuly!");
}
}
catch (IOException e) {
System.out.println(e);
}
try {
socket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
//server
public static void main(String[] args) {
ServerSocket serversocket;
DataOutputStream out;
PrintWriter output;
BufferedReader input;
String linesent;
int lines = 0;
int port=1500;
try {
serversocket = new ServerSocket(port);
System.out.println("Server Waiting For Client On Port " + serversocket.getLocalPort()+"...");
while(true) {
Socket socket= serversocket.accept();
System.out.println("Connection Accepted With This Ip: " +socket.getInetAddress() +" On This Port :" + socket.getPort());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(),true);
String f=input.readLine();
File file;
file = new File(f);
BufferedReader reader = new BufferedReader(new FileReader(f));
if(file.exists())
{
while (reader.readLine() != null)
lines++;
reader.close();
out=new DataOutputStream(socket.getOutputStream());
out.writeInt(lines);
Scanner scanner=new Scanner(file);
while(scanner.hasNext())
{
linesent=scanner.nextLine();
output.println(linesent);
}
}
else {
throw new FileNotFoundException(f);
}
try {
socket.close();
System.out.println("Connection closed by client.");
}
catch (IOException e) {
System.out.println(e);
}
}
}
catch (IOException e) {
System.out.println(e);
}
}
答
那么你为什么不只是更换:
throw new FileNotFoundException(f);
通过
output.println("file not exist");
+0
我之前尝试过,但它没有在客户端程序中通过此错误回答: – 2013-04-10 10:35:37
+0
java.net.SocketException:连接重置 – 2013-04-10 10:36:05
有没有出了问题?你想向你的代码添加一条错误消息? – suspectus 2013-04-10 09:52:04
你的问题是什么? – mthmulders 2013-04-10 09:54:52