我编写了一个 java TCP 服务器程序。我将在我的 PC 上运行该程序。我编写了一个 java TCP 客户端程序,我将在 android 模拟器上运行。我将使用 ip 地址 10.0.2.2 连接到服务器,因为我使用的是 android 模拟器。但是性能很差。近8-10分钟后,服务器正在接收客户端发送的数据。并且模拟器没有从服务器接收任何数据。请看看哪里出错了?
TCP 服务器(在 PC 中运行):
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence=null;
ServerSocket welcomeSocket = new ServerSocket(9000);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
if(clientSentence.equals("IS COMPUTER ON?"))
{
capitalizedSentence = "YES SYSTEM IS ON.";
}
outToClient.writeBytes(capitalizedSentence);
}
}
}
TCP 客户端(在安卓模拟器中运行):
package a.b.c;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class WifitestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
String sentence="IS COMPUTER ON?";
String modifiedSentence=sentence;
Socket clientSocket = new Socket("10.0.2.2", 9000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(sentence);
modifiedSentence = inFromServer.readLine();
TextView a=(TextView)findViewById(R.id.textView1);
a.setText(modifiedSentence);
a.showContextMenu();
clientSocket.close();
}
catch(Exception e)
{
TextView a=(TextView)findViewById(R.id.textView1);
a.setText(e.toString());
a.showContextMenu();
}
}
}