尝试连接两个Android仿真器时出错。
首先我运行Client Emulator 5554然后运行SErver Emulator 5556
另一方CMD我写这个:
telnet localhost 5554
redir add tcp:5000:6000
在客户端单击发送按钮后,我收到错误,没有响应!
我的代码:
服务器
package com.example.socketserver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textIn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (TextView)findViewById(R.id.textView1);
}
public void Start(View v) throws IOException{
Socket socket = null;
ServerSocket serverSocket = new ServerSocket(6000);
socket = serverSocket.accept();
DataInputStream dataInputStream = null;
dataInputStream = new DataInputStream(socket.getInputStream());
textIn.setText(dataInputStream.readUTF());
//Toast.makeText(this, "Listening...", Toast.LENGTH_SHORT).show();
TextView label=(TextView)findViewById(R.id.textView3);
label.setText("Loading...");
serverSocket.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
客户端
package com.example.socketclient;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
public class ClientActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
}
public void Send(View v) throws IOException{
Socket socket = null;
socket = new Socket("10.0.2.2", 5000);
DataOutputStream dataOutputStream = null;
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF("Message from Sender");
if (socket != null){
socket.close();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
}