网络编程 TCP文件上传
1.TCP客户端
(1)建立连接
(2)创建输出流
(3)读取文件
(4)写出文件
(5)断开连接
(6)关闭流
2.TCP服务器端
(1)创建服务
(2)监听客户端连接
(3)获取输入流
(4)文件输出
(5)关闭流
客户端代码:
public class TcoClient{
public static void main(String[] args){
//1.建立连接
Socket socket = new Socket(InetAddress.getByname("127.0.0.1"), 9999);
//2.创建一个输出流
OutputStream os = socket.getOutputStream();
//3.读取文件
FileInputStream is = new FileInputStream(new File("a.jpg"));
byte[] buff = new byte[1024];
int len;
//4.写出文件
while((len = is.read(buff)) != -1){
os.write(buff, 0, len);
}
//通知服务器,传输结束
socket.shutdownOutput();
//确定服务器接收完毕,再断开连接
//接收字符、就用字节的管道流
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff2 = new byte[1024];
int len2;
while((len2 = inputStream.read(buff)) != -1){
bos.write(buff2, 0, len2);
}
System.out.println(bos.toString());
//5.释放资源,从小往大关
bos.close();
inputStream.close();
is.close();
os.close();
socket.close();
}
}
服务端代码
public class TcpServer(){
public static void main(String[] args) throws Exception{
//1.创建服务
ServerSocket serverSocket = new ServerSocket(9999);
//2.监听客户端连接
Socket accept = serverSocket.accept();
//3.获取输入流
InputStream is = accept.getInputStream();
//4.文件输出
//接收文件就要用文件的管道流
FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
byte[] buff = new bytep[1024];
int len;
while((len = is.read(buff)) != -1){
fos.write(buff, 0, len);
}
//通知客户端接收完毕
OutputStream os = accept.getOutputStream();
os.write("已接收完毕,可以断开了".getBytes());
//5.关闭流
fos.close();
is.close();
accept.close();
serverSocket.close();
}
}
本文为看B站狂神视频的笔记,视频地址为:TCP文件上传实现