我想连接2个模拟器实例,这样我就可以在它们之间发送简单的聊天消息。为此,我在一个模拟器上设置了一个服务器,并将其他模拟器设置为客户端。所以我在模拟器5554上运行服务器,在5556上运行客户端。
侦听端口6000的服务器端代码:
public class NewServerActivity extends Activity{
//private TextView tv;
private Thread fst;
private ServerSocket ss;
public static final int SERVERPORT = 6000;
String mClientMsg = "";
protected static final int MSG_ID = 0x1337;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv= (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
this.fst= new Thread(new RunThread());
this.fst.start();
}
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class RunThread implements Runnable{
public void run(){
try{
ss= new ServerSocket();
Socket s= ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
Message m = new Message();
m.what = MSG_ID;
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
}catch(IOException ep){
ep.printStackTrace();
}
}
}
}
在端口5000上建立连接的客户端代码:
public class NewClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private Thread scd;
private String serverIpAddress = "10.0.2.2";
private static final int REDIRECTED_SERVERPORT = 5000;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
this.scd= new Thread(new RunThread1());
this.scd.start();
}
class RunThread1 implements Runnable{
public void run() {
try {
//InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverIpAddress, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
}
我将端口重定向为:
telnet localhost 5554
redir add tcp:5000:6000
一切正常,两个应用程序都启动但是当我点击发送按钮时,服务器端没有响应。我错过了一些东西。