1.服务端读取客户端已有的图片数据
2.通过Socket输出流将数据发给服务端
3.读取服务端反馈信息
4.关闭资源
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class PicServer {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(10007);
Socket accept = server.accept();
InputStream is = accept.getInputStream();
FileOutputStream fos = new FileOutputStream("E:\\server.png");
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
OutputStream out = accept.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
server.close();
accept.close();
}
}
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 {
Socket socket = new Socket("192.168.1.6", 10007);
FileInputStream fis = new FileInputStream("E:\\test.jpg");
OutputStream os = socket.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
}
InputStream is = socket.getInputStream();
socket.shutdownOutput(); // 告诉服务器数据已写完
byte[] bufIn = new byte[1024];
int num = is.read(bufIn);
System.out.println(new String(bufIn, 0, num));
socket.close();
fis.close();
}
}
网友评论