android套接字连接失败?

时间:2013-01-25 19:41:58

标签: java android sockets

我正在编写一个示例聊天程序,它在2个Android手机之间发送消息,所以我编写了以下内容并让手机连接到自身(10.0.2.2或localhost)来测试代码的工作与否。 但看起来像在receivemsg()的线程中,套接字永远不会连接。那么我使用错误的IP地址来引用自己吗?或者我的代码有什么问题?谢谢你的帮助!

package com.example.chatroomprogram;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ClientActivity extends Activity {

    private Handler handler = new Handler();
    public ListView msgView;
    public ArrayAdapter<String> msgList;
//  public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
//          android.R.layout.simple_list_item_1);;
    public String ipaddress;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        Intent intent = getIntent();
        ipaddress=intent.getStringExtra("ipaddress");
        Log.i("123","ip is "+ipaddress);
         msgView = (ListView) findViewById(R.id.listView);

        msgList = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1);
        msgView.setAdapter(msgList);
//      msgView.smoothScrollToPosition(msgList.getCount() - 1);

        Button btnSend = (Button) findViewById(R.id.btn_Send);

        receiveMsg();

        btnSend.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
                //msgList.add(txtEdit.getText().toString());
                sendMessageToServer(txtEdit.getText().toString());
                msgView.smoothScrollToPosition(msgList.getCount() - 1);

            }           
        });

//      receiveMsg();
        //----------------------------
        //server msg receieve
        //-----------------------



        //End Receive msg from server//
    }
    public void sendMessageToServer(String str) {

        final String str1=str;
        new Thread(new Runnable() {

            @Override
            public void run() {
                //String host = "opuntia.cs.utep.edu";
                //String host="10.0.";
                String host2 = "10.0.2.2";
                PrintWriter out = null;

                    Socket socket = null;
                    try {
                        socket = new Socket("10.0.2.2", 8008);
                    } catch (UnknownHostException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        out = new PrintWriter(socket.getOutputStream());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                        Log.i("123","not null");
                    // out.println("hello");
                    out.println(str1);
                    Log.i("123", "hello");
                    out.flush();


            }
        }).start();
            }



    public void receiveMsg()
    {
        new Thread(new Runnable()
        {
            @Override
            public void run() {
                // TODO Auto-generated method stub

                //final  String host="opuntia.cs.utep.edu";
                final String host="10.0.2.2";
                //final String host="127.0.0.1";
                Socket socket = null ;
                BufferedReader in = null;
                try {
                    //socket = new Socket(host,8008);
                    ServerSocket ss = new ServerSocket(8008);
                     socket = ss.accept();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                while(true)
                {
                    String msg = null;
                    try {
                        msg = in.readLine();
                        Log.i("123","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        displayMsg(msg);
                    }
                }

            }
        }).start();


    }

    public void displayMsg(String msg)
    { 
        final String mssg=msg;
        handler.post(new Runnable() {

            @SuppressLint("NewApi")
            @Override
            public void run() {
                // TODO Auto-generated method stub
                msgList.add(mssg);
                msgView.setAdapter(msgList);
                msgView.smoothScrollToPosition(msgList.getCount() - 1);
                Log.i("123","hi");
            }
        });

    }

}

更新:问题解决了,结论:如果你使用AVD,只需使用10.0.2.2;如果您使用实际手机进行调试,则可以使用localhost

1 个答案:

答案 0 :(得分:0)

我的不好......我使用10.0.2.2并且它有效...

相关问题