日食中的套接字通信失败

时间:2012-04-14 09:29:08

标签: android

尝试在手机和PC之间开发简单的套接字通信。我已启用ineternet-uses权限但仍会出现java.net.connectionException错误。我正在eclipse中开发应用程序,我已经尝试将eclipse网络连接设置为本机和代理,但它仍然无法连接。有人可以指出我正确的方向吗?

PC和仿真器都在同一网络中。 这是我试图执行的代码:

客户端:Android应用:

public class AndyActivity extends Activity {
/** Called when the activity is first created. */
private TextView serverIp;
private Button connectPhones;
private boolean connected=false;
private String serverIpAddress="192.16.11.12";
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);      
connectPhones = (Button) findViewById(R.id.button1);
    serverIp = (TextView) findViewById(R.id.textView1);                 
    connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener(){
    @Override
    public void onClick(View v){
        serverIp.setText("lovely");
        if(!connected){
            serverIpAddress = serverIp.getText().toString();
            if (!serverIpAddress.equals("")) {
                Thread cThread = new Thread(new ClientThread());
                cThread.start();
            }

        }
    }
};

public class ClientThread implements Runnable {

public void run() {
        try {
            Log.d("ClientActivity", "C: Starting");
            //InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            int SERVERPORT = 9191;
        //    Socket socket = new Socket(serverAddr,SERVERPORT );

            Socket socket = new Socket("192.16.11.12",9192);
            Log.d("ClientActivity", "C: Connected");
            connected = true;
            while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // where you issue the commands
                  //      out.println("Hey Server!");
                        Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }
            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }

}
}

服务器端:

public class server1 {
  public static void main (String [] args ) throws IOException {
    // create socket
    ServerSocket servsock = new ServerSocket(9191);
    while (true) {
      System.out.println("Waiting...");

      Socket sock = servsock.accept();
      System.out.println("Accepted connection : " + sock);

      System.out.println("ok");
      sock.close();
      }
    }
}

0 个答案:

没有答案