java - 程序在 ObjectInputStream 阻塞

标签 java android swing sockets serialization

我的程序是一个简单的服务器端 java 应用程序,用于接收字符串。 我的程序在输入流处挂起。 我在这里阅读了各种讨论,正如指出的那样,我首先创建了输出流并在创建输入流之前将其刷新。

我仍然面临同样的问题。

服务器端代码-JAVA SWING APP

//Server.java
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class Server extends JFrame {
    JTextField txtenter;
    JTextArea txtadisplay;
    ObjectOutputStream output;
    ObjectInputStream input;

    @SuppressWarnings("deprecation")
    public Server() {
        super("SERVER");
        Container c = getContentPane();

        txtenter = new JTextField();
        txtenter.setEnabled(false);
        txtenter.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sendData(e.getActionCommand());
            }
        });
        c.add(txtenter, BorderLayout.SOUTH);

        txtadisplay = new JTextArea();
        txtadisplay.setEditable(false);
        c.add(new JScrollPane(txtadisplay), BorderLayout.CENTER);

        setSize(300, 150);
        show();
    }

    public void runServer() {
        ServerSocket ss;
        Socket s;
        int counter = 1;

        try {
            // create a seversocket
            ss = new ServerSocket(2222, 100);

            while (true) {

                // wait for the connection
                System.out.println("naval");
                txtadisplay.setText("Wating for the Connection...");
                txtadisplay.append("current IP:" + InetAddress.getLocalHost().getHostAddress());
                txtadisplay.append("current PORT:" + ss.getLocalPort());

                // establishing connection
                System.out.println("naval2");
                s = ss.accept();
                output = new ObjectOutputStream(s.getOutputStream());
                output.flush();
                input = new ObjectInputStream(s.getInputStream());
                System.out.println("naval3");
                txtadisplay.append("Conection" + counter + "receivedfrom:" + s.getInetAddress().getHostName());
                System.out.println("naval4");
                // getting input/output

                System.out.println("naval5");
                output = new ObjectOutputStream(s.getOutputStream());
                output.flush();
                input = new ObjectInputStream(s.getInputStream());
                System.out.println("staream created");
                System.out.println("naval6");
                // processing connection
                String message;

                do {
                    txtadisplay.append("under DO loop");
                    message = (String) input.readObject();
                    txtadisplay.append("" + message);
                    txtadisplay.setCaretPosition(txtadisplay.getText().length());
                } while (!message.equals("CLIENT>>>TERMINATE"));

                txtadisplay.append("User Terminated Connection...");

                input.close();
                s.close();
                ++counter;
            }
        } catch (Exception e) {

        }
    }

    public void sendData(String s) {
        try {
            output.writeObject("SERVER>>>" + s);
            txtadisplay.append("SERVER>>>" + s);
        } catch (Exception e) {

        }
    }

    public static void main(String args[]) {
        Server ser = new Server();

        ser.addWindowListener(new WindowAdapter() {
            public void WindowClosing(final WindowEvent e) {
                System.exit(0);
            }
        });
        ser.runServer();
    }

}

客户端代码 - 安卓应用

package info.androidhive.speechtotext;


import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

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

import static java.sql.DriverManager.println;


public class MainActivity extends Activity {

    /**
     * Declarations
     */
    private TextView txtSpeechInput;

    private ImageButton btnSpeak;

    String str;

    private final int REQ_CODE_SPEECH_INPUT = 100;

    private String serverIpAddress = "";

    private boolean connected = false;

    TextView textIn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

        // hide the action bar
        getActionBar().hide();

        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                promptSpeechInput();
            }
        });

    }

    /**
     * Showing google speech input dialog
     */
    private void promptSpeechInput() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                getString(R.string.speech_prompt));
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    getString(R.string.speech_not_supported),
                    Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * Receiving speech input
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    txtSpeechInput.setText(result.get(0));
                    str = result.get(0);
                    setContentView(R.layout.activity_main);
                    Log.d("1- naval", " client oncreate");

                    Button button = (Button) findViewById(R.id.send);
                    textIn = (TextView) findViewById(R.id.textin);
                    /**
                     * Setting the text box with default value
                     */
                    textIn.setText(str);
                    Log.d("settext", " 2-naval");
                    /**
                     * Here we need to fill in textin from MainActivity,
                     * where we received the speech API text
                     */
                    button.setOnClickListener(new View.OnClickListener() {

                                                  @Override
                                                  public void onClick(View arg0) {
                                                      if (!connected) {
                                                          serverIpAddress = "192.168.0.4";
                                                          if (!serverIpAddress.equals("")) {
                                                              Thread cThread = new Thread(new ClientThread());
                                                              cThread.start();
                                                          }
                                                      }
                                                  }
                                              }
                    );


                }
            }
        }
    }

    public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: Connecting...");
                Socket socket = new Socket(serverAddr,2222);
                PrintWriter out = null;
                out.println(str);
                connected = true;
                while (connected) {
                    try {
                        Log.d("ClientActivity", "C: Sending command.");
                        out = new PrintWriter(
                                new BufferedWriter(new OutputStreamWriter(
                                        socket.getOutputStream())), true);
                        // WHERE YOU ISSUE THE COMMANDS
                        // out.println("Hey Server!");
                        Log.d("ClientActivity", "C: Sent.");
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }
                }
                socket.close();
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}

最佳答案

根据其他论坛伙伴的建议。在客户端更改为 outputStream 有帮助。 谢谢..

只是一个快速查询:虽然应用程序运行良好。消息从 Android 应用程序到达 Java 桌面应用程序有 1-2 秒的延迟。这是正常的还是我需要一些微调。

代码

Android Client

MainActivity.java

package info.androidhive.speechtotext;


import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

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

import static java.sql.DriverManager.println;


public class MainActivity extends Activity {

    /**
     * Declarations
     */
    private TextView txtSpeechInput;

    private ImageButton btnSpeak;

    String str;

    private final int REQ_CODE_SPEECH_INPUT = 100;

    private String serverIpAddress = "";

    private boolean connected = false;

    TextView textIn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

        // hide the action bar
        getActionBar().hide();

        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                promptSpeechInput();
            }
        });

    }

    /**
     * Showing google speech input dialog
     */
    private void promptSpeechInput() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                getString(R.string.speech_prompt));
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
            Toast.makeText(getApplicationContext(),
                    getString(R.string.speech_not_supported),
                    Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * Receiving speech input
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    txtSpeechInput.setText(result.get(0));
                    str = result.get(0);
                    setContentView(R.layout.activity_main);
                    Log.d("1- naval", " client oncreate");

                    Button button = (Button) findViewById(R.id.send);
                    textIn = (TextView) findViewById(R.id.textin);
                    /**
                     * Setting the text box with default value
                     */
                    textIn.setText(str);
                    Log.d("settext", " 2-naval");
                    /**
                     * Here we need to fill in textin from MainActivity,
                     * where we received the speech API text
                     */
                    button.setOnClickListener(new View.OnClickListener() {

                                                  @Override
                                                  public void onClick(View arg0) {
                                                      if (!connected) {
                                                          serverIpAddress = "192.168.0.4";
                                                          if (!serverIpAddress.equals("")) {
                                                              Thread cThread = new Thread(new ClientThread());
                                                              cThread.start();
                                                          }
                                                      }
                                                  }
                                              }
                    );


                }
            }
        }
    }

    public class ClientThread implements Runnable {
        Socket socket = null;


        public void run() {
            try {
                socket = new Socket("192.168.0.4", 2222); //use the IP address of the server

                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

                oos.writeObject(str);

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {

                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        }
    }
}

Java 服务器

//Server.java
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class Server extends JFrame {
    JTextField txtenter;
    JTextArea txtadisplay;
    ObjectOutputStream output;
    ObjectInputStream input;

    @SuppressWarnings("deprecation")
    public Server() {
        super("SERVER");
        Container c = getContentPane();

        txtenter = new JTextField();
        txtenter.setEnabled(false);
        txtenter.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sendData(e.getActionCommand());
            }
        });
        c.add(txtenter, BorderLayout.SOUTH);

        txtadisplay = new JTextArea();
        txtadisplay.setEditable(false);
        c.add(new JScrollPane(txtadisplay), BorderLayout.CENTER);

        setSize(300, 150);
        show();
    }

    public void runServer() {
        ServerSocket ss;
        Socket s;
        int counter = 1;

        try {
            // create a seversocket
            ss = new ServerSocket(2222, 100);

            while (true) {

                // wait for the connection
                System.out.println("naval");
                txtadisplay.setText("Wating for the Connection...");
                txtadisplay.append("current IP:" + InetAddress.getLocalHost().getHostAddress());
                txtadisplay.append("current PORT:" + ss.getLocalPort());

                // establishing connection
                System.out.println("naval2");
                s = ss.accept();
                txtadisplay.append("Conection" + counter + "receivedfrom:" + s.getInetAddress().getHostName());
                output = new ObjectOutputStream(s.getOutputStream());
                output.flush();
                input = new ObjectInputStream(s.getInputStream());
                System.out.println("naval3");

                System.out.println("naval4");
                // getting input/output


                String message;

                do {
                   // txtadisplay.append("under DO loop");
                    message = (String) input.readObject();
                    txtadisplay.append("" + message);
                    txtadisplay.setCaretPosition(txtadisplay.getText().length());
                } while (!message.equals("CLIENT>>>TERMINATE"));

                txtadisplay.append("User Terminated Connection...");

                input.close();
                s.close();
                ++counter;
            }
        } catch (Exception e) {

        }
    }

    public void sendData(String s) {
        try {
            output.writeObject("SERVER>>>" + s);
            txtadisplay.append("SERVER>>>" + s);
        } catch (Exception e) {

        }
    }

    public static void main(String args[]) {
        Server ser = new Server();

        ser.addWindowListener(new WindowAdapter() {
            public void WindowClosing(final WindowEvent e) {
                System.exit(0);
            }
        });
        ser.runServer();
    }

}

关于java - 程序在 ObjectInputStream 阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965029/

相关文章:

Java——画一个三角形

java - 如何在 Android Studio 中实现折叠文本?

java - 将行插入数据库后 JTable 不更新

java - 如何在JSP页面中显示数据库表

Tomcat 8 上 Eclipse 项目的 WebServlet 中的 java.lang.NullPointerException

java - 为什么反转 strings.xml 中字符串数组中的声明顺序会发生变化?

java - ParentBottom View 的 View.Gone 导致问题

java - swing jtable默认显示多行

java - 如果我的 3 个文本字段都有输入,我的 JButton 仅在我的文本字段上执行 set.Text

java - Google Pub/Sub 模拟器 - 使用 Java 的 HTTP.POST 发布消息会抛出 400 错误请求