服务端

package com.cn.tcp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
/**
* 编写一个服务端可以给多个客户端发送图片。(多线程)
* @author zhiyong
*
*/
/**
* 服务端
* @author zhiyong
*
*/
public class ImageServer extends Thread{
Socket socket = null;
//使用该集合是用于存储ip地址的, 注意共享
static HashSet<String> ips = new HashSet<String>();

public ImageServer(Socket socket) {
this.socket = socket;
}
public void run() {
try {
//获取到socket的输出流对象
OutputStream outputStream = socket.getOutputStream();
//获取图片的输入流对象
FileInputStream fileInputStream = new FileInputStream(new File("f:/cool.png"));
//读取图片数据,把数据写出
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地址对象
System.out.println("下载的ip是:" + ip);
if(ips.add(ip)){
System.out.println("恭喜" + ip + "用户成功下载!当前下载人数是:" + ips.size());
}

//关闭资源
fileInputStream.close();
socket.close();
} 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.cn.tcp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 下载图片的客户端
* @author zhiyong
*
*/
public class ImageClient {
public static void main(String[] args) throws IOException, IOException {
System.out.println(InetAddress.getLocalHost());
//建立tcp服务
Socket socket = new Socket(InetAddress.getByName("192.168.18.111"), 9090);
//获取socket的输入流对象
InputStream inputStream = socket.getInputStream();
//获取文件的输出流对象,为了把获取到的文件写出
FileOutputStream fileOutputStream = new FileOutputStream(new File("f:/jj.png"));
//边读编写
byte[] buf = new byte[1024];
int length = 0;
while((length = inputStream.read(buf)) != -1){
fileOutputStream.write(buf, 0, length);
}
//关闭资源
fileOutputStream.close();
socket.close();
}
}