E
E
Envywewok2019-10-25 16:18:50
Java
Envywewok, 2019-10-25 16:18:50

How to read data in Java from ethernet port?

I’m not looking for a ready-made solution, at least help in which direction to look / dig (maybe I’m setting up the converter in the wrong way, or vice versa on the other side of the problem).
There is a sensor that sends data about its location to the moxa NPort 5650-8-DTL converter, via com port, and it transmits the same data via ethernet to the computer. You need to read the data that comes. I tried to do it in java using a socket, but due to my poor knowledge of networks, I'm not sure that I'm reading what I need. Here is the first screen of the port settings. 5db2f530ce97e253480238.png. On my computer, I set 192.168.10.1 and in wireshark I see how something goes with the ip that is on the converter. 5db2f5c888c01360691514.png.

String hostname = "192.168.10.4";
        int port = 4004;

        try (Socket socket = new Socket(hostname, port)) {
            InputStream input = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(input);

            int character;
            StringBuilder data = new StringBuilder();

            while ((character = reader.read()) != -1) {
                data.append((char) character);
            }
            System.out.println(data);

        } catch (UnknownHostException ex) {
            System.out.println("Server not found: " + ex.getMessage());
        } catch (IOException ex) {
            System.out.println("I/O error: " + ex.getMessage());
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sergey, 2019-10-28
@Envywewok

https://en.wikipedia.org/wiki/Berkeley_Sockets
www.java2s.com/Tutorials/Java/Java_Network/0020__J... must be added

socket.bind(new InetSocketAddress("localhost",  port));
socket.connect(new InetSocketAddress("localhost",  port));

connect()
connect() Establishes a connection to the server. Returns an integer representing the error code: 0 indicates success and -1 indicates an error.
bind()
bind() binds a socket to a specific address. When a socket is created with socket(), it is associated with some address family, but not with a specific address. Before a socket can accept incoming connections, it must be bound to an address.
...
After connecting a Socket object, we can use its input and output streams using the getInputStream() and getOutputStream() methods, respectively.
...

M
mayton2019, 2019-10-25
@mayton2019

We must first understand the roles. Are you a client or a server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question