服务器端
public class ServiceSocket {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8899);
while(true){
System.out.println("服务器启动...");
Socket socket = serverSocket.accept();
System.out.println("感知到客户端连接...");
new Thread(new MyThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class MyThread implements Runnable{
private Socket socket ;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
OutputStream outputStream = null ;
FileInputStream fileInputStream = null;
try {
outputStream = socket.getOutputStream();
fileInputStream = new FileInputStream(new File("H:/test.png"));
byte[] bytes = new byte[64] ;
int len = -1 ;
while ( (len = fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if(outputStream!=null) outputStream.close();
if(fileInputStream!=null) fileInputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
客户端
public class ClientSocket {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8899);
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[64] ;
FileOutputStream fileOutputStream = new FileOutputStream(new File("H:/out.png"));
int len = -1 ;
while ((len = inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
inputStream.close();
fileOutputStream.close();
}
}