whyclxw
2020-11-02 f8b7ca9bc6b51c137053f16c1c7150a11aba13c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.modbus.data;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;
 
public class SocketClient {
 
    // socket发送和读取数据
    public static boolean SocketComm(byte[] bytedata, String ip)throws InterruptedException {
        boolean res_t = false;
        InputStream in = null;
        OutputStream out = null;
        Socket socket = new Socket();
        ByteBuffer bytebuffer_for_socket_RX = ByteBuffer.allocate(1500);
        try {
            socket.connect(new InetSocketAddress(ip, 502), 5000);
            socket.setSoTimeout(3000);
            if (socket != null) {
                in = socket.getInputStream();
                out = socket.getOutputStream();
                // ----------------- clear rx buff for tcp resend packet
                // ----------------//
                byte[] rx_buf_t = new byte[1024];
                // ----------------------------------------------------------------------//
                bytebuffer_for_socket_RX.order(ByteOrder.BIG_ENDIAN);
                bytebuffer_for_socket_RX.clear();
                // --------------------- socket write
                // -----------------------------------//
                // byte[] b = makeCommBuf(cmd, bf);
                //System.err.println("发送数据:"+ComFn.bytesToHexString(bytedata,bytedata.length));
                Date d1 = new Date();
                int rx_read_time_out = 0;
                // int rx_len = 0;
                // System.err.println("TX: " + ComFn.bytesToHexString(b,
                // b.length));
                out.write(bytedata);
                out.flush();
                res_t=true;
            }
        } catch (IOException e) {
            res_t=false;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }
        return res_t;
    }
 
}