1

Im' writing a sample chat program that sends message between 2 android phones, so I wrote the following and let a phone connect to itself(10.0.2.2 or localhost) to test it the code works or not. But looks like in the thread of receivemsg(), the socket is never connected. So did I use the wrong ip address to refer to myself? or does my code have something wrong? thank you for your help!

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");
            }
        });

    }

}

update: Problem solved, conclusion: if you use AVD, just use 10.0.2.2; if you use an actual phone to debug, you can use localhost

4

1 回答 1

0

我的错...我使用了 10.0.2.2 并且它有效...

于 2013-01-25T19:55:20.320 回答