我看了毕老师的视频,编写Tcp文件复制的时候总会出现Connection refused: connect或者Connection reset,请问这是为什么啊?下面是我的程序,请大神指点:
服务端:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpCopyServer {
public static void main(String[] args) throws Exception {
// 建立连接
ServerSocket s = new ServerSocket(10004);
Socket ss = s.accept();
String ip = ss.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");
//源是网络输入流,读取信息
BufferedReader bufr = new BufferedReader(new InputStreamReader(ss.getInputStream()));
//目的是copy 写入文件中去
//BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy1.txt")));
PrintWriter pw = new PrintWriter(new FileWriter("copy1.txt"),true);
String line = null;
while((line = bufr.readLine())!=null){
pw.write(line);
}
//给出反馈信息
PrintWriter pw1 = new PrintWriter(ss.getOutputStream(),true);
pw1.write("上传成功");
pw.close();
ss.close();
s.close();
}
}
客户端:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class TcpCopyClient {
public static void main(String[] args) throws Exception {
//1.建立连接
Socket s = new Socket("192.168.25.166",10004);
//源是文件
BufferedReader bufr = new BufferedReader(new FileReader("a.txt"));
//目的是网络输出流
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
String line = null;
while((line = bufr.readLine())!=null){
pw.write(line);
}
s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1.
//读取服务端传回来的反馈信息
BufferedReader buff = new BufferedReader(new InputStreamReader(s.getInputStream()));
String len = buff.readLine();
System.out.println(len);
bufr.close();
s.close();
}
}
|
|