客户端:
package com.cy.client;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端上传图片到服务端
*/
public class PicClient {
public static void main(String[] args) throws Exception {
//创建文件输入流对象
FileInputStream fileInputStream = new FileInputStream("F:\\img.jpg");
//创建socket对象
Socket socket = new Socket("localhost",8000);
//获取输出流对象
OutputStream outputStream = socket.getOutputStream();
int temp=0;
while ((temp=fileInputStream.read())!=-1){
outputStream.write(temp);
}
//添加流输入完成标志
socket.shutdownOutput();
//接收到服务端的响应
InputStream inputStream = socket.getInputStream();
byte[] buffer=new byte[1024];
int length = inputStream.read();
System.out.println(new String(buffer,0,length));
//添加流输入完成的标志
socket.shutdownInput();
//关闭操作
inputStream.close();
outputStream.close();
socket.close();
fileInputStream.close();
}
}
服务端:
package com.cy.server;
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.nio.charset.StandardCharsets;
/**
* 接受客户端上传的图片
*/
public class PicServer {
public static void main(String[] args) throws IOException {
//创建服务端对象,开放端口
ServerSocket serverSocket = new ServerSocket(8000);
//创建服务端的socket
Socket socket = serverSocket.accept();
//获取输入流对象
InputStream inputStream = socket.getInputStream();
//创建文件输出流对象
FileOutputStream fileOutputStream = new FileOutputStream("fav.jpg");
int temp=0;
while ((temp=inputStream.read())!=-1){
fileOutputStream.write(temp);
}
//添加流输出完成的标志
// socket.shutdownOutput();
//上传图片结束后给予客户端响应
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传成功".getBytes(StandardCharsets.UTF_8));
// //添加流输出完成的标志
// socket.shutdownInput();
outputStream.close();
inputStream.close();
fileOutputStream.close();
socket.close();
}
}