1

当我使用 Windows 运行 eclipse Android 模拟器连接套接字时,它是成功的。但是,当我使用 Mac os lion 运行“相同”代码时,模拟器显示“不幸的是客户端测试已停止!”请帮我解决这个问题。我已经添加了互联网权限!

package com.example.testclientokok;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        Socket socket=new Socket(InetAddress.getLocalHost(), 8888);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

服务器部分

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class MyServer {

 public static void main(String[] args){
 ServerSocket serverSocket = null;
 Socket socket = null;
 DataInputStream dataInputStream = null;
 DataOutputStream dataOutputStream = null;

 try {
  serverSocket = new ServerSocket(8888);
  System.out.println("Listening :8888");
 } catch (IOException e) {
 // TODO Auto-generated catch block
  e.printStackTrace();
}

while(true){
  try {
   socket = serverSocket.accept();
   dataInputStream = new DataInputStream(socket.getInputStream());
   dataOutputStream = new DataOutputStream(socket.getOutputStream());
   System.out.println("ip: " + socket.getInetAddress());
   System.out.println("message: " + dataInputStream.readUTF());
   dataOutputStream.writeUTF("Hello!");
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
  finally{
   if( socket!= null){
    try {
      socket.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
 }
}

if( dataInputStream!= null){
 try {
  dataInputStream.close();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}

if( dataOutputStream!= null){
 try {
  dataOutputStream.close();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
     }
    }
   }
  }
 }
}
4

1 回答 1

0

如果我理解正确,您正在您的机器上执行 MyServer,您还运行模拟器。如果模拟器中运行的 Activity 想要与 MyServer 建立连接,那么它应该使用以下 IP 地址:10.0.2.2(而不是 localhost,它引用了 emualor 环回接口)。

请参阅http://developer.android.com/tools/devices/emulator.html#networkaddresses

于 2012-10-22T17:38:34.927 回答