使用TCP实现客户端向服务端上传图片
程序员文章站
2024-03-22 18:51:34
...
服务端
package wanfeng;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPserver1 {
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象
ServerSocket ss = new ServerSocket(9000);
// 监听客户端连接
Socket s = ss.accept();
InputStream inputStream=s.getInputStream();
//接受到的文件输送到目标文件夹
OutputStream outputStream=new FileOutputStream("D:\\hello\\H1.JPG");
byte[] buffer=new byte[1024];
int len=0;
while((len=inputStream.read(buffer))!=-1)
{
outputStream.write(buffer,0,len);
}
outputStream.close();
inputStream.close();
s.close();
}
}
客户端
package wanfeng;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Random;
public class TCPclient1 {
public static void main(String[] args) throws IOException {
// 创建客户端Socket对象
Socket socket = new Socket("127.0.0.1",9000);
OutputStream outputStream=socket.getOutputStream();
InputStream inputStream=new FileInputStream("D:\\360downloads\\222.JPG");//输入流读取图片
byte[] buffer=new byte[1024];
int len=0;
while((len=inputStream.read(buffer))!=-1)
{
outputStream.write(buffer,0,len);//向服务端输送
}
outputStream.close();
inputStream.close();
socket.close();
}
}