1 /**
 2  * 1、创建TCP服务端,TCP客户端
 3  * 2、服务端等待客户端连接,客户端连接后,服务端向客户端写入图片
 4  * 3、客户端收到后进行文件保存
 5  * @author Administrator
 6  *
 7  */
 8 public class ServerTcpListener implements Runnable{
 9 
10     public static void main(String[] args) {
11 
12         try {
13             final ServerSocket server = new ServerSocket(33456);
14             
15             
16             Thread th = new Thread(new Runnable() {
17                 public void run() {
18                     while (true) {
19                         try {
20                             System.out.println("开始监听...");
21                             Socket socket = server.accept();
22                             System.out.println("有链接");
23                             send(socket);
24                         } catch (Exception e) {
25                         }
26                     }
27                 }
28             });
29 
30             th.run(); //启动线程运行
31         } catch (Exception e) {
32             e.printStackTrace();
33         }
34     }
35     
36     @Override
37     public void run() {
38         
39     }
40     
41     public static void send(Socket socket) {
42         byte[] inputByte = null;
43         int length = 0;
44         DataOutputStream dos = null;
45         FileInputStream fis = null;
46         try {
47             try {
48                 File file = new File("D:/1.png");
49                 fis = new FileInputStream(file);
50                 dos = new DataOutputStream(socket.getOutputStream());
51                 
52                 inputByte = new byte[1024];
53                 while ((length = fis.read(inputByte, 0, inputByte.length)) > 0) {
54                     dos.write(inputByte, 0, length);
55                     dos.flush();
56                 }
57                
58             } finally {
59                 if (fis != null)
60                     fis.close();
61                 if (dos != null)
62                     dos.close();
63                 if (socket != null)
64                     socket.close();
65             }
66         } catch (Exception e) {
67         }
68     }
69 }
ServerTcpListener.java

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2022-12-23
  • 2021-11-06
  • 2022-12-23
  • 2022-01-12
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
  • 2021-07-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案