本帖最后由 无奈的年华ˊ 于 2014-4-22 14:04 编辑
哪位哥们帮忙看看,为什么老是报 java.net.SocketException: Connection reset 异常 ?????!
客户端
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.net.UnknownHostException;
- public class SocketTest {
- public static void main(String[] args) throws UnknownHostException, IOException {
- /*
- * 通过客户端读取本地文件发送给服务端
- * */
-
- System.out.println("TCP客户端启动.....");
- //创建客户端对象
- Socket s = new Socket("169.254.41.237", 20000);
-
-
- //读取本地文件
- BufferedReader bufr = new BufferedReader(new FileReader("c:\\新建文件夹txt"));
-
- //获取客户端对象输出流,将数据发送给服务端
- //BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
-
- String leng = null;
- while((leng=bufr.readLine())!=null){
- out.println(leng);
- }
-
- //发送结束标记
- s.shutdownOutput();
-
- //获取客户端对象的读取流、接收服务端发回的数据
- BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- String lineIn = bufIn.readLine();
-
- System.out.println(lineIn);
-
-
- //关闭资源
- bufIn.close();
- out.close();
- bufr.close();
- s.close();
- }
复制代码
服务端
- import java.io.BufferedReader;
- 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 ServerSocketTest {
- public static void main(String[] args) throws IOException {
- /*
- * 获取客户端发送来的数据,并将数据存储到本地。收到后将接收结果发送给客户端
- * */
-
- System.out.println("服务器启动.........");
- // 1、创建服务端对象、并监听一个端口
- ServerSocket ss = new ServerSocket(20000);
- // 2、获取客户端端对象
- Socket s = ss.accept();
- //System.out.println(s.getInetAddress().getHostAddress()+"...连接了!");
-
- //获取客户端对象输入流
- BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
-
- //创建文件输出流,明确目的
- //BufferedWriter bufw = new BufferedWriter(new FileWriter("c:\\复件"));
- PrintWriter pw = new PrintWriter(new FileWriter("c:\\复件.txt"),true);
-
- String line = null;
- while((line=bufIn.readLine())!=null){
- pw.println(line);
- }
-
- //获取客户端对象输出流,将数据发送给客户端
- PrintWriter out = new PrintWriter(s.getOutputStream(),true);
-
- //发送数据
- out.println("上传成功");
-
- //关闭服务
- pw.close();
- s.close(); //服务器一般在数据传输完成后先将客户端的连接关闭
- ss.close();
-
- }
- }
复制代码
谢谢......!!!!!!!!!!!!!!!!
|