有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Python TCP/IP PLC客户端到Java语言的演示

我有一个用python制作的西门子s1200 plc TCP/IP客户端演示。我在Youtube上找到了它:https://www.youtube.com/watch?v=5KLLeQeB2EY

我的问题是,如何将这些代码翻译成java程序。我目前正在做一个项目,将数据从plc读取到java客户机(后来从java读取到plc),我目前被这个项目卡住了

这个python演示在运行时在控制台上写入“testi1”字符串,我希望从“output1”数据块中获得更多数据。附加的数据块图片

请帮忙

干杯


import socket

HOST = '192.168.0.1' #plc ip
PORT = 2000 # plc port

if __name__ == "__main__":
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as conn:
        conn.connect((HOST, PORT))
        print(conn.recv(1024).decode('UTF-8', errors='ignore')) #.decode('UTF-8', errors='ignore') erases some nonsense output


data block "output1"


共 (1) 个答案

  1. # 1 楼答案

    一个简单的Ping模型

    客户端类

    import java.io.OutputStream;
    import java.io.InputStream
    import java.net.InetSocketAddress;
    import java.net.Socket;
    
    
    class Client 
    {
     public static void main(String args[])
     {
      try(Socket client=new Socket())
      {
       client.connect(new InetSocketAddress("localhost",8000));
    
       Scanner scanner=new Scanner(System.in);
       String input;
    
     
       try(OutputStream out=client.getOutputStream();
            InputStream in=client.getInputStream())
       {
        while(!(input=scanner.nextLine()).equals("Bye"))
        { 
         out.write(input.getBytes());
    
         System.out.println("Server said "+new String(in.readAllBytes()));
        }
       }
       catch(IOException ex){ex.printStackTrace();}     
      }
      catch(IOException ex){ex.printStackTrace();}
     }
    }
    

    服务器类

    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    
    class Server 
    {
     public static void main(String args[])
     {
      try(ServerSocket server=new ServerSocket())
      {
       server.bind(new InetSocketAddress("localhost",8000));
       System.out.println("Server Online");
       
       try(Socket client=server.accept())
       {
         try(InputStream in=client.getInputStream();
             OutputStream out=client.getOutputStream())
         {         
          while(true)
          { 
           String response=new String(in.readAllBytes());
           if(response.equals("Bye")){break;}
           else{out.write(("Echo "+response).getBytes());}
          }
         }
       catch(IOException ex){ex.printStackTrace();}
      }
      catch(IOException ex){ex.printStackTrace();}
     }
    }
    

    您可以根据自己的目的对其进行建模