Java TCP套接字编程(二)文件传输
2021-06-06 12:02
标签:main str 断开连接 close throws leo 服务 output aos 客户端: 服务器: Java TCP套接字编程(二)文件传输 标签:main str 断开连接 close throws leo 服务 output aos 原文地址:https://www.cnblogs.com/zzzstudy/p/14613945.htmlJava TCP套接字编程(二)文件传输
package com.zzz.net;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8080); //创建一个socket
OutputStream os = socket.getOutputStream(); //创建一个输出流
FileInputStream fis = new FileInputStream("picture1.jpg"); //读取文件
byte[] buffer = new byte[1024]; //写出文件
int len;
while ((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
//通知服务器,传输完毕
socket.shutdownOutput();
//确定服务器接收完毕,才能够断开连接
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//关闭资源
baos.close();
is.close();
fis.close();
os.close();
socket.close();
}
}
package com.zzz.net;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080); //创建服务
Socket socket = serverSocket.accept(); //监听连接
InputStream is = socket.getInputStream(); //获取输入流
FileOutputStream fos = new FileOutputStream("receive1.jpg"); //文件输出
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//通知客户端我接收完毕了
OutputStream os = socket.getOutputStream();
os.write("我接收完毕了,你可以断开了".getBytes());
//关闭资源
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}