【发布时间】:2011-01-13 18:39:54
【问题描述】:
我想在 2 Emulator 中创建一个服务器和一个客户端来写入和读取数据。 我为服务器编写代码:
public class ServerActivity extends Activity {
/** Called when the activity is first created. */
private ServerSocket serverSocket = null;
private TextView tv;
public static final int SERVERPORT = 4444;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv= (TextView) findViewById(R.id.myTextView);
try {
Connect();
} catch (IOException e) {
// TODO Auto-generated catch block
tv.setText("Not connected");
e.printStackTrace();
}
}
public void Connect() throws IOException
{
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("10.0.2.15", 4444));
while(true)
{
Socket socket = serverSocket.accept();
tv.setText("Connected...");
}
}
客户端代码
public class ClientActivity extends Activity {
/** Called when the activity is first created. */
private Button bt;
private TextView tv;
@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);
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Socket socket = new Socket("10.0.2.2", 4445);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
tv.setText("Error2");
e.printStackTrace();
}
}
});
}
}
我设置了重定向:
telnet localhost 5554
redir add tcp:4445:4444
但它没有连接....请帮助我。我很感激。
【问题讨论】:
-
我从来没有找到一种方法来做到这一点。祝你好运。
-
@Falmarri:NickT 发布的内容很棒!
标签: android