我正在编写一个示例Java Server / Android Client程序,以学习如何在Android上使用套接字。这是一套简单的程序;客户端向服务器发送一串文本,服务器将其回送给客户端。服务器使用的是直接运行的Java,客户端是使用Jelly Bean版本系统的Android智能手机。虽然我可以让Android设备作为服务器运行,但我很难让它作为客户端工作。
我的服务器代码如下:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPIPServer3
{
public static void main(String argv[]) throws Exception
{
// Declaration Section:
// Declare a server socket and a client socket for the server
// Declare an input and an output stream
ServerSocket echoServer = null;
String line;
DataInputStream is;
BufferedReader br;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(9999);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
br = new BufferedReader(new InputStreamReader(is));
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true)
{
line = br.readLine();
System.out.println(line);
os.println(line);
os.flush();
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
我的客户端代码如下:
package com.example.androidtcpclient3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "10.0.2.2";
//private String serverIpAddress = "10.1.200.100";
private static final int REDIRECTED_SERVERPORT = 9999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
String line;
DataInputStream is;
BufferedReader br;
PrintWriter out;
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
is = new DataInputStream(socket.getInputStream());
br = new BufferedReader(new InputStreamReader(is));
line = br.readLine();
tv.setText(line);
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
}
我无法让程序执行语句“line = br.readLine();”在Android客户端上。出于某种原因,每次在代码中到达时,此语句总是抛出异常。在客户端程序的执行中,这会导致字符串“Error3”被写入客户端的TextView小部件。但是,我已经能够确认服务器可以从客户端成功读取数据。 readLine()方法似乎显示客户端和服务器之间的不对称行为。
任何帮助解决此问题都将不胜感激。
更新:我的堆栈跟踪如下:
07-18 13:56:36.802: W/System.err(2164): android.os.NetworkOnMainThreadException
07-18 13:56:36.832: W/System.err(2164): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-18 13:56:36.842: W/System.err(2164): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
07-18 13:56:36.842: W/System.err(2164): at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
07-18 13:56:36.852: W/System.err(2164): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
07-18 13:56:36.862: W/System.err(2164): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
07-18 13:56:36.872: W/System.err(2164): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
07-18 13:56:36.882: W/System.err(2164): at java.io.DataInputStream.read(DataInputStream.java:84)
07-18 13:56:36.882: W/System.err(2164): at java.io.InputStreamReader.read(InputStreamReader.java:244)
07-18 13:56:36.894: W/System.err(2164): at java.io.BufferedReader.fillBuf(BufferedReader.java:130)
07-18 13:56:36.902: W/System.err(2164): at java.io.BufferedReader.readLine(BufferedReader.java:354)
07-18 13:56:36.902: W/System.err(2164): at com.example.androidtcpclient3.ClientActivity$ClientThread$1.onClick(ClientActivity.java:75)
07-18 13:56:36.912: W/System.err(2164): at android.view.View.performClick(View.java:4204)
07-18 13:56:36.922: W/System.err(2164): at android.view.View$PerformClick.run(View.java:17355)
07-18 13:56:36.932: W/System.err(2164): at android.os.Handler.handleCallback(Handler.java:725)
07-18 13:56:36.932: W/System.err(2164): at android.os.Handler.dispatchMessage(Handler.java:92)
07-18 13:56:36.942: W/System.err(2164): at android.os.Looper.loop(Looper.java:137)
07-18 13:56:36.952: W/System.err(2164): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-18 13:56:36.952: W/System.err(2164): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 13:56:36.962: W/System.err(2164): at java.lang.reflect.Method.invoke(Method.java:511)
07-18 13:56:36.972: W/System.err(2164): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-18 13:56:36.972: W/System.err(2164): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-18 13:56:36.983: W/System.err(2164): at dalvik.system.NativeStart.main(Native Method)