黑马程序员技术交流社区

标题: tcp上传文件异常 [打印本页]

作者: dubei1993    时间: 2016-6-9 22:49
标题: tcp上传文件异常
package cn.itcast_03;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
//tcp上传文件,这是服务器端
public class ServerDemo {
public static void main(String[] args) throws IOException {
  // 创建服务器端Socket对象
  ServerSocket ss = new ServerSocket(9100);
  // 创建客户端监听对象,返回Socket对象
  Socket s = ss.accept();
  // 封装通道内流
  BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
  // 封装目录
  BufferedWriter bw = new BufferedWriter(new FileWriter("copy.txt"));
  // 复制文件
  String line = null;
  while ((br.readLine()) != null) {
   bw.write(line);
   bw.newLine();
   bw.flush();
  }
  bw.close();
  s.close();
}
}

package cn.itcast_03;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
//tcp协议客户端
public class ClientDemo {
public static void main(String[] args) throws IOException {
//创建客户端Socket接口
Socket s=new Socket("localhost",9100);
//封装文件目录
BufferedReader br=new BufferedReader(new FileReader("aaa.txt"));
//封装通道内流
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line=null;
while((br.readLine())!=null){
  bw.write(line);
  bw.newLine();
  bw.flush();
}
br.close();
s.close();
}
}



作者: dubei1993    时间: 2016-6-9 22:51
Exception in thread "main" java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
        at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
        at sun.nio.cs.StreamDecoder.read(Unknown Source)
        at java.io.InputStreamReader.read(Unknown Source)
        at java.io.BufferedReader.fill(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at java.io.BufferedReader.readLine(Unknown Source)
        at cn.itcast_03.ServerDemo.main(ServerDemo.java:24)

作者: Fangjie    时间: 2016-6-10 10:49
把while((br.readLine())!=null){改成while((line=br.readLine())!=null)试下
作者: dubei1993    时间: 2016-6-10 10:59
Fangjie 发表于 2016-6-10 10:49
把while((br.readLine())!=null){改成while((line=br.readLine())!=null)试下

嗯。好了。多谢




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2