编写本地端与服务端完成图片的传输(可扩展)
程序员文章站
2022-05-14 18:16:19
...
日常练习
在日常生活中,经常用到图片上传服务,在学习了一些Socket知识后便想要自己实现一下,若有不对,希望指出。
因本人没有服务器,所以代码在两台电脑间测试,此代码在两台电脑间运行正常。
注:本代码旨在练习Socket的TCP传输过程,故未进行相关异常处理
下面是本地端:
package Socket;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;
/**
* 客户端:
* 创建Socket连接
* 创建缓冲区读取本地文件
* 将本地文件通过Socket流发送出去
*
* 创建缓冲区接受服务器返回的消息
*
* */
public class TcpSendPic_Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("此处填写ip地址",10001);
File file = new File("G://图片//4K.jpg");
BufferedInputStream bufr = new BufferedInputStream( new FileInputStream(file));
BufferedOutputStream bufOut = new BufferedOutputStream(s.getOutputStream());
BufferedInputStream bufIn = new BufferedInputStream(s.getInputStream());
int len = 0;
byte[] data = new byte[1024];
while((len = bufr.read(data))!=-1) {
System.out.println("sending");
bufOut.write(data,0,len);
bufOut.flush();
}
/** 结束标记 */
s.shutdownOutput();
System.out.println("Send done");
byte[] b = new byte[1024];
int num = bufIn.read(b);
String msg = new String(b,0,num);
System.out.println(msg);
}
}
下面是服务器端:
package Socket;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器端:
* 创建ServerSocket并获得客户端的对象
* 创建缓冲区接收客户端发送的数据
*
*
*
* */
public class TcpReceivePic_Servel {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10001);
Socket s = ss.accept();
File file = new File("C:\\Users\\HP\\Desktop\\123\\test2.jpg");
BufferedInputStream bufIn = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream(file));
BufferedOutputStream bufOut = new BufferedOutputStream(s.getOutputStream());
int len = 0;
byte[] buf = new byte[1024];
while((len = bufIn.read(buf)) != -1) {
bufos.write(buf,0,len);
bufos.flush();
}
bufOut.write("upload OK".getBytes());
bufOut.flush();
bufos.close();
s.close();
ss.close();
}
}
我的另一篇文章 共享剪切板