向繼電器發送socket請求(python+java)


近日,有一需求,向連接在內網的繼電器發送socket請求,加以控制。原本並不復雜,只是io流/socket轉換的問題,實操中卻出現python代碼沒問題,java代碼執行無響應的問題,問題很好定位:沒有發送正確的請求指令。進而確定是編碼的問題,python預設全局編碼格式為utf-8,java端只需指定請求字節碼為utf-8即可。

python實現: 

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "NYA"

import socket

soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

address=('172.18.20.188',5002)

soc.connect(address)

message="on1"
message="off1"
message="read1"

#res=soc.recv(512)
#print res
soc.send(message)

total=[]
i=0
while True:
    res=soc.recv(1)
    if i>8:
        total.append(res)
    i+=1
    if str(res)=='1': break

#print res
then=''.join(total)
print then
soc.close()

java實現:

import java.io.*;
import java.net.Socket;
import java.util.regex.Pattern;

public class TestSocket {

    public static void main(String[] args) {

        /*
        * command:
        *   on1 off1 read1
        *   on2 off2 read2
        * */

        try {

            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

            boolean flag = true;

            while (flag) {

                System.out.println("輸入信息: ");
                String str = input.readLine();


                if ("bye".equals(str)) {
                    flag = false;
                } else {
                    String s = sendCommand(str);
                    System.out.println(s);
                }
            }
            input.close();
            System.err.println("good bye");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static String sendCommand(String command) {
        String result;
        String ip = "172.18.20.188";
        int port = 5000;
        Socket socket = null;
        try {
            socket = new Socket(ip,port);

            socket.setSoTimeout(1000); // read 超時

            OutputStream outputStream = socket.getOutputStream();
            byte[] receive = new byte[1];

            byte[] bytes = command.getBytes("UTF-8"); // 轉碼 ×××

            outputStream.write(bytes);

            InputStream inputStream = socket.getInputStream();
            StringBuilder sb = new StringBuilder();
            int i = 0 ;
            while (true) {
                inputStream.read(receive);
                String now = new String(receive);
                if (i > 8) sb.append(now);
                if (i > 10) {
                    if (isInteger(now)) break;
                }
                i++;
            }
            result =  sb.toString();
        } catch (Exception e) {
            //e.printStackTrace();
            result="err";
        }

        // 釋放socket連接
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM