package com.zyf.day24;
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;
/**
* 编写一个服务端可以给多个客户端发送图片。(多线程)
* @author root
*
*/
public class ImageServer extends Thread{
Socket socket;
//使用该集合是用于存储ip地址的
static HashSet<String> ips = new HashSet<String>();
public ImageServer(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
//获取到socket输出流对象
OutputStream outputStream = socket.getOutputStream();
//获取图片的输入流对象
FileInputStream fileInputStream = new FileInputStream("C:\\1.jpg");
//读取图片数据,把数据写出
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf))!=-1){
outputStream.write(buf,0,length);
}
String ip = socket.getInetAddress().getHostAddress();//socket getInetAddress()获取对方的IP地址
if(ips.add(ip)){
System.out.println("恭喜" + ip + "同学成功下载" + ips);
}
System.out.println("下载的ip是:" + ip);
//关闭资源
fileInputStream.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 {
//建立tcp的服务,并且要监听一个端口
ServerSocket serverSocket = new ServerSocket(9090);
//接受用的的连接
while(true){
Socket socket = serverSocket.accept();
new ImageServer(socket).start();
}
}
}
package com.zyf.day24;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
//下载图片的客户端
public class ImageClient {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Socket socket = new Socket(InetAddress.getLocalHost(),9090);
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("c:\\1.jpg");
byte[] buf = new byte[1024];
int length = 0;
while((length = inputStream.read()) != -1){
fileOutputStream.write(buf,0,length);
}
//关闭资源
fileOutputStream.close();
socket.close();
}
}