简体   繁体   English

Java:如何使用套接字发送和接收数据?

[英]Java: How send and receive data using socket?

I'm building a middleware, where I need to constantly read what is happening in my device, so I build this class: 我正在构建一个中间件,在这里我需要不断阅读设备中正在发生的事情,因此我建立了这个类:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Valter
 */
public class Middleware {

    public static void main(String args[]) {
        try {
            // ip and port where is my device  
            Socket socket = new Socket("192.168.1.4", 2001);

            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());

            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

            // i need send this parameter to my device 
            dataOutputStream.writeUTF("}Rv!");

            String answer = dataInputStream.readUTF();
            System.out.println("Answer:"+answer);

            dataInputStream.close();
            dataOutputStream.close();
            socket.close();

        } catch (UnknownHostException ex) {
            System.out.println("UNKNOW HOST EXCEPTION");
        } catch (IOException ex) {
            System.out.println(" IOEXCEPTION");
            System.out.println(ex.getMessage());
        }
    }
}

Output: 输出:

IOEXCEPTION Connection reset IOEXCEPTION连接重置

What's wrong with my class? 我班上怎么了?

I don't know if this is what is causing your problem, but you are not flushing the output stream before attempting to read a response from the input stream. 我不知道这是否是导致您出现问题的原因,但是您在尝试从输入流中读取响应之前没有刷新输出流。 Try: 尝试:

dataOutputStream.writeUTF("}Rv!");
dataOutputStream.flush();

Does your device really understand the output of writeUTF()?and produce the correct input for readUTF()? 您的设备是否真的了解writeUTF()的输出?并为readUTF()产生正确的输入? Check the Javadoc. 检查Javadoc。 I don't think it likely. 我认为不太可能。

'Connection reset' usually means you have written to a connection that was already closed by the other end, which is already an application protocol error, and it may indicate prior application protocol errors. “连接重置”通常意味着您已写入另一端已经关闭的连接,这已经是应用程序协议错误,并且可能表示先前的应用程序协议错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM