1

Windows で eclipse Android エミュレーターを実行してソケットを接続すると、成功しました。ただし、Mac OS ライオンを使用して「同じ」コードを実行すると、エミュレーターに「残念ながらクライアント テストが停止しました!!」と表示されます。これを解決するのを手伝ってください。

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 を実行しています。エミュレーターで実行されているアクティビティが MyServer との接続を確立する必要がある場合は、次の IP アドレスを使用する必要があります: 10.0.2.2 (エミュレーターまたはループバック インターフェイスを参照する localhost ではありません)。

http://developer.android.com/tools/devices/emulator.html#networkaddressesを参照してください

于 2012-10-22T17:38:34.927 に答える