向继电器发送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();
    }

}
posted @ 2019-01-03 10:39  来兮子宁  阅读(1138)  评论(0编辑  收藏  举报