【发布时间】:2015-11-05 01:14:16
【问题描述】:
我的程序是一个简单的服务器端 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;
}
}
}
}
【问题讨论】:
-
你的客户端代码在哪里?
-
更新原帖
-
'hangs at input stream 是什么意思?为什么要在同一个套接字上创建两个 ObjectOutputStream?为什么要尝试使用带有 ObjectInputStream 的 PrintWriter 读取数据?当您没有向输入流发送任何内容时,您为什么会对输入流阻塞感到惊讶?为什么您不从服务器中的两个对象输出流中的任何一个读取客户端中的任何内容?有什么问题?
-
PrintWriter out = null; out.println(str);-> 空指针 -
首先,您的客户端正在发送文本,而您的服务器正在等待序列化对象 - 您的客户端应该将字符串发送到 ObjectOutputStream。解决此问题后,请检查您的客户端是否确实在发送数据(使用日志记录或逐步调试器)。您的服务器可能会一直阻塞,直到它真正收到一些东西。
标签: java android swing sockets serialization