tcp通讯_一个服务器可以给多个客户端发送图片

来源:互联网 发布:彩票数据分析软件开发 编辑:程序博客网 时间:2024/05/16 11:48
服务端
  1. package com.cn.tcp;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.OutputStream;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. import java.util.HashSet;
  9. /**
  10. * 编写一个服务端可以给多个客户端发送图片。(多线程)
  11. * @author zhiyong
  12. *
  13. */
  14. /**
  15. * 服务端
  16. * @author zhiyong
  17. *
  18. */
  19. public class ImageServer extends Thread{
  20. Socket socket = null;
  21. //使用该集合是用于存储ip地址的, 注意共享
  22. static HashSet<String> ips = new HashSet<String>();
  23. public ImageServer(Socket socket) {
  24. this.socket = socket;
  25. }
  26. public void run() {
  27. try {
  28. //获取到socket的输出流对象
  29. OutputStream outputStream = socket.getOutputStream();
  30. //获取图片的输入流对象
  31. FileInputStream fileInputStream = new FileInputStream(new File("f:/cool.png"));
  32. //读取图片数据,把数据写出
  33. byte[] buf = new byte[1024];
  34. int length = 0;
  35. while((length = fileInputStream.read(buf)) != -1){
  36. outputStream.write(buf, 0, length);
  37. }
  38. String ip = socket.getInetAddress().getHostAddress();//socket.getInetAddress()获取对方的ip地址对象
  39. System.out.println("下载的ip是:" + ip);
  40. if(ips.add(ip)){
  41. System.out.println("恭喜" + ip + "用户成功下载!当前下载人数是:" + ips.size());
  42. }
  43. //关闭资源
  44. fileInputStream.close();
  45. socket.close();
  46. } catch (IOException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }
  50. }
  51. public static void main(String[] args) throws IOException {
  52. //建立tcp服务端,并且要监听一个端口
  53. ServerSocket serverSocket = new ServerSocket(9090);
  54. while(true){//不断接收用户的连接
  55. Socket socket = serverSocket.accept();
  56. new ImageServer(socket).start();//启动多线程
  57. }
  58. }
  59. }
客户端
  1. package com.cn.tcp;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.InetAddress;
  7. import java.net.Socket;
  8. import java.net.UnknownHostException;
  9. /**
  10. * 下载图片的客户端
  11. * @author zhiyong
  12. *
  13. */
  14. public class ImageClient {
  15. public static void main(String[] args) throws IOException, IOException {
  16. System.out.println(InetAddress.getLocalHost());
  17. //建立tcp服务
  18. Socket socket = new Socket(InetAddress.getByName("192.168.18.111"), 9090);
  19. //获取socket的输入流对象
  20. InputStream inputStream = socket.getInputStream();
  21. //获取文件的输出流对象,为了把获取到的文件写出
  22. FileOutputStream fileOutputStream = new FileOutputStream(new File("f:/jj.png"));
  23. //边读编写
  24. byte[] buf = new byte[1024];
  25. int length = 0;
  26. while((length = inputStream.read(buf)) != -1){
  27. fileOutputStream.write(buf, 0, length);
  28. }
  29. //关闭资源
  30. fileOutputStream.close();
  31. socket.close();
  32. }
  33. }
0 0
原创粉丝点击