简体   繁体   English

如何在android手机中运行android聊天应用程序?

[英]How to run android chat application in android phones?

I have done an android application for a simple chat application.I am using command prompt as server and chat is done with emulator as client.This application is not working when we put the apk in phone using WIFI. 我已经完成了一个简单的聊天应用程序的android应用程序。我使用命令提示符作为服务器,并且使用模拟器作为客户端进行聊天。当我们使用WIFI将apk放在手机中时,此应用程序无法正常工作。 Android client program is shown below package edu.UTEP.android; Android客户端程序显示在软件包edu.UTEP.android下;

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

import android.app.Activity;
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;
import android.widget.Toast;

public class AndyChatActivity 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);;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         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() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(AndyChatActivity.this, "here", Toast.LENGTH_SHORT).show();
                final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
                String msg=txtEdit.getText().toString();
                Toast.makeText(AndyChatActivity.this, msg, Toast.LENGTH_SHORT).show();
                //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() {
                // TODO Auto-generated method stub
                //String host = "https://www.tudens.in";
                String host="192.168.1.5";
                //Toast.makeText(AndyChatActivity.this, "thread Opened", Toast.LENGTH_SHORT).show();

                //String host2 = "127.0.0.1";
                PrintWriter out;
                try {

                    Socket socket = new Socket(host, 8008);
                    out = new PrintWriter(socket.getOutputStream());
                    Log.d("1", "good");

                    // out.println("hello");
                    out.println(str1);
                    Log.d("2", "gd");
                    out.flush();
                    Log.d("", "hello");
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("", "hello222");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("", "hello4333");
                }

            }
        }).start();
            }



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

                final  String host="192.168.1.5";
                //final String host="10.0.2.2";
                //final String host="localhost";
                Socket socket = null ;
                BufferedReader in = null;
                try {
                    socket = new Socket(host,8008);
                } 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.d("","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() {

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

    }

}

java server program is shown below : Java服务器程序如下所示:

import java.io.*;
import java.net.*; 
import java.util.*;

/**
 * A simple chat server implemented using TCP/IP sockets. A client can
 * connect to this server and send messages to other clients. The chat
 * server receives messages from clients and broadcast them to all the
 * connected clients. A message is an arbitrary text and is also
 * printed on stdout. The default port number is 8008.
 *
 * <pre>
 *  Usage: java ChatServer
 * </pre>
 *
 * @author Yoonsik Cheon
 */
public class ChatServer {

    private static final String USAGE = "Usage: java ChatServer";

    /** Default port number on which this server to be run. */
    private static final int PORT_NUMBER = 8008;

    /** List of print writers associated with current clients,
     * one for each. */
    private List<PrintWriter> clients;

    /** Creates a new server. */
    public ChatServer() {
        clients = new LinkedList<PrintWriter>();
    }

    /** Starts the server. */
    public void start() {
        System.out.println("AndyChat server started on port "
                           + PORT_NUMBER + "!"); 
        try {
            ServerSocket s = new ServerSocket(PORT_NUMBER); 
            for (;;) {
                Socket incoming = s.accept(); 
                new ClientHandler(incoming).start(); 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("AndyChat server stopped."); 
    }

    /** Adds a new client identified by the given print writer. */
    private void addClient(PrintWriter out) {
        synchronized(clients) {
            clients.add(out);
        }
    }

    /** Adds the client with given print writer. */
    private void removeClient(PrintWriter out) {
        synchronized(clients) {
            clients.remove(out);
        }
    }

    /** Broadcasts the given text to all clients. */
    private void broadcast(String msg) {
        for (PrintWriter out: clients) {
            out.println(msg);
            out.flush();
        }
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println(USAGE);
            System.exit(-1);
        }
        new ChatServer().start();
    }

    /** A thread to serve a client. This class receive messages from a
     * client and broadcasts them to all clients including the message
     * sender. */
    private class ClientHandler extends Thread {

        /** Socket to read client messages. */
        private Socket incoming; 

        /** Creates a hander to serve the client on the given socket. */
        public ClientHandler(Socket incoming) {
            this.incoming = incoming;
        }

        /** Starts receiving and broadcasting messages. */
        public void run() {
            PrintWriter out = null;
            try {
                out = new PrintWriter(
                        new OutputStreamWriter(incoming.getOutputStream()));

                // inform the server of this new client
                ChatServer.this.addClient(out);

                out.print("Welcome to AndyChat! ");
                out.println("Enter BYE to exit."); 
                out.flush();

                BufferedReader in 
                    = new BufferedReader(
                        new InputStreamReader(incoming.getInputStream())); 
                for (;;) {
                    String msg = in.readLine(); 
                    if (msg == null) {
                        break; 
                    } else {
                        if (msg.trim().equals("BYE")) 
                            break; 
                        System.out.println("Received: " + msg);
                        // broadcast the receive message
                        ChatServer.this.broadcast(msg);
                    }
                }
                incoming.close(); 
                ChatServer.this.removeClient(out);
            } catch (Exception e) {
                if (out != null) {
                    ChatServer.this.removeClient(out);
                }
                e.printStackTrace(); 
            }
        }
    }
}

You have to change your host address to 10.0.2.2 . 您必须将主机地址更改为10.0.2.2 Because for android emulators host address are different. 因为对于android模拟器,主机地址不同。 You can read more about it here. 您可以在此处了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM