该程序复制到开发工具中即可调试或使用
================服务端==================
/* * 小程序:编写一个程序可以给多个客户端发送图片(多线程); * 图片下载服务端 */
package com.lin.michael;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
public class DownloadServer extends Thread{
Socket socket;
//使用HashSet存储ip地址
static HashSetips = new HashSet();
public DownloadServer(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
//3.从socket获取输入流对象(输出通道,给客户端发送信息);
OutputStream outputStream = socket.getOutputStream();
//4.获取图片的输入字节流对象
FileInputStream fileInputStream = new FileInputStream("c:\\DSC_0303.jpg");
//5.读取图片数据,把数据写出
byte[] buf = new byte[1024];
int length = 0;
while((length=fileInputStream.read(buf))!=-1){
outputStream.write(buf,0,length);
}
//获取客户端的饿IP地址
String ip = socket.getInetAddress().getHostAddress();
if(ips.add(ip)){
System.out.println("恭喜"+ip+"成功下载,当前成功下载的人数" + ips.size() + "个");
}
//6.关闭资源
fileInputStream.close();
socket.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException{
//1.建立服务端的tcp服务
ServerSocket serverSocket = new ServerSocket(9090);
while(true){
//2.接受用户的连接,获取Socket对象;
Socket socket = serverSocket.accept();
new DownloadServer(socket).start();
}
}
}
================客户端===================
/*
* 下载客户端;
*/
package com.lin.michael;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class DownloadClient {
public static void main(String[] args) throws UnknownHostException, IOException{
//1.建立tcp的Socket
Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
//2.从socket获取输入流对象
InputStream inputStream = socket.getInputStream();
//3.穿件文件的输出字节流通道
FileOutputStream fileOutputStream = new FileOutputStream("e:\\copy.jpg");
//4.边读编写出
byte[] buf = new byte[1024];
int length = 0;
while((length=inputStream.read(buf))!=-1){
fileOutputStream.write(buf, 0, length);
}
//5.关闭资源
fileOutputStream.close();
socket.close();
}
}