本帖最后由 猪猪fly侠 于 2015-5-5 15:01 编辑
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/*
* 客户端
* 1、创建客户端点 连接服务器
* 2、读取客户端已有数据
* 3、通过socket输入流将数据发送给服务端
* 4、读取服务器反馈信息
* 5、关闭
*
*/
public class TcpPicDemo {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket s = new Socket("127.0.0.1",10007);
FileInputStream fis = new FileInputStream("c:\\1.jpeg");
OutputStream os = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf))!=-1){
os.write(buf,0,len);
}
//告诉服务端数据已写完
s.shutdownInput();
InputStream is = s.getInputStream();
byte[] bufin = new byte[1024];
int num = is.read(bufin);
System.out.println(new String(bufin,0,num));
fis.close();
s.close();
}
}
class PicServer{
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(10007);
Socket s = ss.accept();
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("c:\\server.jpeg");
byte[] buf = new byte[1024];
int len = 0;
//循环结束不了
while((len = in.read(buf))!=-1){
fos.write(buf, 0, len);
}
OutputStream os = s.getOutputStream();
os.write("传输完成".getBytes());
fos.close();
s.close();
ss.close();
}
}
数据传输已完成但是会抛异常
异常信息:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at com.itheima.day24.PicServer.main(TcpPicDemo.java:70)
|