在Android模拟器上运行的客户端无法创建套接字

时间:2015-03-07 15:46:16

标签: java android client

StackOverflow中提到的讨论 - 对我没有帮助

我试图让客户端在Android模拟器上运行,连接到我在同一台机器上运行的服务器上的服务器。 服务器配置为侦听端口5000。 服务器似乎不是问题所在。当我在eclipse上运行客户端时,他们可以打开一个套接字并进行通信。 当我尝试在Android模拟器上运行Client类时,mainActivity会告诉客户端在创建它时进行连接。 但是由于某种原因,dbugging流程到达catch块,而不是创建套接字。

我也尝试使用client.connect("10.0.2.2",5000);,但它没有帮助。

MainActivity.java

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Client client = new Client(this);
    try {
        client.connect("192.168.1.10",5000);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Client.java

   package com.example.oshri.p;

import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;


public class Client extends Observable implements Runnable {
    MainActivity creatingActivity; // the activity that creates Client

  private Socket socket;
  private BufferedReader br;
  private PrintWriter pw;
  private boolean connected;
  private int port=5555; //default port
  private String hostName="localhost";//default host name

  public Client(MainActivity activity) {
        connected = false;
        this.creatingActivity = activity;
   }

  public void connect(String hostName, int port) throws IOException {
      if(!connected)
      {
         this.hostName = hostName;
         this.port = port;
         socket = new Socket(hostName,port);
         //get I/O from socket
         br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         pw = new PrintWriter(socket.getOutputStream(),true);

           connected = true;
         //initiate reading from server...
         Thread t = new Thread(this);
         t.start(); //will call run method of this class
      }
  }

  public void sendMessage(String msg) throws IOException
  {
        if(connected) {
            pw.println(msg);
      } else throw new IOException("Not connected to server");
  }

  public void disconnect() {
        if(socket != null && connected)
      {
        try {
            socket.close();
        }catch(IOException ioe) {
            //unable to close, nothing to do...
        }
        finally {
            this.connected = false;
        }
      }
  }

  public void run() {
       String msg = ""; //holds the msg recieved from server
       try {
          while(connected && (msg = br.readLine())!= null)
          {
              creatingActivity.displayServerAnswer("Server:"+msg);

             this.setChanged();
                 this.notifyObservers(msg);
          }
       }
       catch(IOException ioe) { }
       finally { connected = false; }
  }

  public boolean isConnected() {
        return connected;
  }


  public int getPort(){
          return port;
      }

  public void setPort(int port){
          this.port = port;
      }

  public String getHostName(){
          return hostName;
      }

  public void setHostName(String hostName){
          this.hostName = hostName;
      }
}

1 个答案:

答案 0 :(得分:0)

@greenapps指出了这个问题: 套接字是在主要活动中创建的。

@Squonk指出了问题,IP应该是10.0.2.2 - 模拟器中用于连接到模拟器运行的机器的本地主机的转换地址

代码已编辑:

MainActivity.java

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ClientThread clientThread = new ClientThread(this);
    try {
        clientThread.startClientThread("10.0.2.2",5000);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

ClientThread.java

package com.example.oshri.parkit;

import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Observable;


public class ClientThread extends Observable implements Runnable {
  MainActivity creatingActivity; // the activity that creates ClientThread
  private Socket socket; //Uses to connect to the server
  private BufferedReader br; //For reading input from server.
  private PrintWriter pw; //For writing output to server.
  private boolean connected; //Status of client.
  private int port=5555; //default port
  private String hostName="localhost";//default host name

  public ClientThread(MainActivity activity) {
        connected = false;
        this.creatingActivity = activity;
   }

  public void startClientThread(String hostName, int port) throws IOException {
      if(!connected)
      {
         this.hostName = hostName;
         this.port = port;

         Thread t = new Thread(this);
         t.start(); //will call run method of this class, that first thing will create a client socket(cannot create socket in main thread)
      }
  }

  public void sendMessage(String msg) throws IOException
  {
        if(connected) {
            pw.println(msg);
      } else throw new IOException("Not connected to server");
  }

  public void disconnect() {
        if(socket != null && connected)
      {
        try {
            socket.close();
        }catch(IOException ioe) {
            //unable to close, nothing to do...
        }
        finally {
            this.connected = false;
        }
      }
  }

  private void connect(){
      // create socket to connect the server
      try {
          socket = new Socket(hostName, port);
      }
      catch(SocketException e){
          System.out.println("client socket could not be created");
      }
      catch (UnknownHostException e){
          System.out.println("UnknownHostException");
      }
      catch (IOException e){
          System.out.println("IOException");
      }

      // create buffers for socket IO
      try{
          br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          pw = new PrintWriter(socket.getOutputStream(),true);
      }
      catch (IOException e){
          System.out.println("socket buffers could not be created");
      }

  connected = true;
  }
  public void run() {
       connect(); //connects the server

   String msg = ""; //holds the msg recieved from server
   try {
      while(connected && (msg = br.readLine())!= null)
      {
         //System.out.println("Server:"+msg);
          creatingActivity.displayServerAnswer("Server:"+msg);

         //notify observers//
         this.setChanged();
        //notify+send out recieved msg to Observers
             this.notifyObservers(msg);
      }
   }
   catch(IOException ioe) { }
   finally { connected = false; }
  }
  public boolean isConnected() {
        return connected;
  }


  public int getPort(){
          return port;
      }

  public void setPort(int port){
          this.port = port;
      }

  public String getHostName(){
          return hostName;
      }

  public void setHostName(String hostName){
          this.hostName = hostName;
      }
}