场景
Java中Socket通信-服务端和客户端双向传输字符串实现:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108488556
在上面实现服务端与客户端双向的通信传输字符串之后,客户端怎样向服务端发送照片。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
首先在服务端的java项目中新建一个接收照片的方法
//服务端接收来自客户端发送的照片
public static void getImageFromClient() throws IOException {
byte[] byteArray = new byte[2048];
ServerSocket serverSocket = new ServerSocket(8088);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
int readLength = inputStream.read(byteArray);
FileOutputStream imageOutputStream = new FileOutputStream(new File("D:\\badao.png"));
while (readLength !=-1)
{
imageOutputStream.write(byteArray,0,readLength);
readLength = inputStream.read(byteArray);
}
imageOutputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
然后在main方法中调用该方法。
这里指定的照片的路径就是获取服务端发来之后存储的路径。
然后在客户端新建发送照片的方法
//客户端发送照片到服务端
public static void sendImageToServer() throws IOException {
String imageFile = "C:\\Users\\admin6\\Desktop\\gzh.png";
FileInputStream imageStream = new FileInputStream(new File(imageFile));
byte[] byteArray = new byte[2048];
System.out.println("socket begin =" + System.currentTimeMillis());
Socket socket = new Socket("localhost",8088);
System.out.println("socket end ="+System.currentTimeMillis());
OutputStream outputStream = socket.getOutputStream();
int readLength = imageStream.read(byteArray);
while (readLength!=-1)
{
outputStream.write(byteArray,0,readLength);
readLength = imageStream.read(byteArray);
}
outputStream.close();
imageStream.close();
socket.close();
}
这里的图片路径是要发送给服务端的照片的路径。
然后在main方法中调用该方法。
首先运行服务端的main方法,然后运行客户端的main方法,之后去D盘下就会接收到bao.png这张照片了。