java实现上传图片(tcp)
程序员文章站
2022-07-10 20:27:08
...
client
package cn.dss.studayTcp.上传图片;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("客户端开启");
Socket socket = new Socket("192.168.43.60", 6666);
// 发送数据
FileInputStream fileInputStream = new FileInputStream("c://2.png");
final OutputStream outputStream = socket.getOutputStream();
byte[] bytes = new byte[1024];
int num = 0;
while ((num = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, num);
}
socket.shutdownOutput();
// 接收数据
InputStream inputStream = socket.getInputStream();
byte[] bytes1 = new byte[1024];
final int read = inputStream.read(bytes1);
final String s = new String(bytes1, 0, read);
System.out.println(s);
}
}
服务端
package cn.dss.studayTcp.上传图片;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("服务端开启");
ServerSocket serverSocket = new ServerSocket(6666);
Socket accept = serverSocket.accept();
// 接收数据
InputStream inputStream = accept.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("2.jpg");
byte[] bytes = new byte[1024];
int num = 0;
while ((num = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, num);
fileOutputStream.flush();
}
// 发回服务端数据
final OutputStream outputStream = accept.getOutputStream();
outputStream.write("上传成功了".getBytes());
outputStream.flush();
}
}
上一篇: java实现图片上传
下一篇: Java实现图片分片上传