程序在ObjectInputStream处阻塞

时间:2015-08-12 12:19:06

标签: 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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

正如同伴论坛成员所建议的那样。在客户端更改为outputStream有帮助。 感谢..

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

CODE

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

//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();
    }

}