【问题标题】:Creating a messaging application (Wifi)创建消息传递应用程序 (Wifi)
【发布时间】:2013-04-12 09:43:48
【问题描述】:

我对 Android 应用程序开发有点陌生。我已经创建了一个非常简单的应用程序,可以打开/关闭设备的手电筒。 我想尝试创建一个消息应用程序,当你们都连接到 Wifi 时,您可以在其中与朋友聊天。有点像“WhatsApp”、“Viber”等。 如果您能给我指导并帮助我了解如何开发这样的应用程序,我将非常高兴。

非常感谢, 奥廖尔。

【问题讨论】:

    标签: android wifi chat messaging


    【解决方案1】:

    为此,您需要创建服务器程序,该程序将验证用户名和密码以及差异用户之间的通信..等,并且您需要根据用户查询发送响应。 对于任何网络通信应用程序都包含两个组件:

    1. 服务器
    2. 客户

    对于 WhatsApp android 应用程序,它是一个与 WhatsApp 服务器通信的客户端应用程序。

    将数据从一个客户端交换到另一个客户端的服务器,客户端可能是桌面、android 手机、iPhone 等

    通常聊天程序将使用套接字实现,这取决于您选择的架构和技术。

    【讨论】:

    • 所以你的意思是我首先需要一个带有数据库的服务器来存储所有的消息?
    • 是的。还有其他方法,但根本不建议这样做。
    • 我明白了。你能给我一个简单的应用程序的建议,我可以作为初学者开发吗?谢谢。
    【解决方案2】:

    使用这个:

    聊天服务器端

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Enumeration;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class ChatServerSide extends Activity implements View.OnClickListener {
    
    private ServerSocket serverSocket;
    Handler updateConversationHandler;
    Thread serverThread = null;
    Button btnSendMsg;
    EditText etInputMessage;
    TextView tvOutputMessage;
    TextView tvMyIp;
    Socket socket;
    public static final int SERVERPORT = 6000;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_main_activity);
        iniUi();
        iniListener();
    
        updateConversationHandler = new Handler();
    
        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();
        tvMyIp.setText("Waiting devices on " + getIpAddress());
    
    }
    
    private void iniUi() {
        tvMyIp = (TextView) findViewById(R.id.tvMyIp);
        btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
        etInputMessage = (EditText) findViewById(R.id.etInputMesage);
        tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
    }
    
    private void iniListener() {
        btnSendMsg.setOnClickListener(this);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
    
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    
    }
    
    @Override
    public void onClick(View view) {
        try {
    
            String str = etInputMessage.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true
            );
            tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: "   + str + "\n");
            etInputMessage.setText("");
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    class ServerThread implements Runnable {
    
        public void run() {
            socket = null;
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {
    
                try {
                    socket = serverSocket.accept();
                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    class CommunicationThread implements Runnable {
    
        private Socket clientSocket;
        private BufferedReader input;
    
        public CommunicationThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
    
            try {
                this.input = new BufferedReader(new   InputStreamReader(this.clientSocket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                String read = null;
                try {
    
                    read = input.readLine();
                    if (read == null) {
                        read = "Client has leave the chat";
                        socket.close();
                        updateConversationHandler.post(new updateUIThread(read));
                        break;
                    }
                    updateConversationHandler.post(new updateUIThread("Client Says: " +   read));
    
    
            }catch(IOException e){
                e.printStackTrace();
            }
    
        }
    }
    
    }
    
    class updateUIThread implements Runnable {
    private String msg;
    
    public updateUIThread(String str) {
        this.msg = str;
    }
    
    @Override
    public void run() {
        tvOutputMessage.setText(tvOutputMessage.getText().toString() + msg + "\n");
    }
    
    }
    
    private String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                        .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();
    
                    if (inetAddress.isSiteLocalAddress()) {
                        ip += inetAddress.getHostAddress() + "\n";
                    }
    
                }
    
            }
    
        } catch (SocketException e) {
            e.printStackTrace();
            ip += "Something Wrong! " + e.toString() + "\n";
        }
    
        return ip;
      }
    }
    

    聊天客户端

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class ChatClientSide extends Activity implements View.OnClickListener {
    
    private Handler handler = new Handler();
    private Socket socket;
    Button btnSendMsg;
    EditText etInputMessage;
    TextView tvOutputMessage;
    Handler updateConversationHandler;
    TextView tvMyIp;
    private static final int SERVERPORT = 6000;
    private static String SERVER_IP = "";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_main_activity);
        iniUi();
        iniListener();
        SERVER_IP = ActivityMain.ipToConnect;
        updateConversationHandler = new Handler();
        receiveMsg();
    
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private String getServerIp(Intent intent) {
        Bundle bundle = intent.getExtras();
        String ip = bundle.getString("destAdress");
        tvMyIp.setText("Is connected to " + ip);
        return ip;
    }
    
    private void iniUi() {
        tvMyIp = (TextView) findViewById(R.id.tvMyIp);
        btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
        etInputMessage = (EditText) findViewById(R.id.etInputMesage);
        tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
    }
    
    private void iniListener() {
        btnSendMsg.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View view) {
        try {
    
            String str = etInputMessage.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true
            );
            tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: "   + str + "\n");
            etInputMessage.setText("");
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public void receiveMsg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String host = SERVER_IP;
    
                BufferedReader in = null;
                try {
                    socket = new Socket(host, SERVERPORT);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                while (true) {
                    String msg = null;
                    try {
                        msg = in.readLine();
                        //msgList.add(msg);
                    } catch (IOException e) {
                        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() {
                tvOutputMessage.setText(tvOutputMessage.getText().toString() + "Server Says: " + mssg + "\n");
            }
        });
    }
    }
    

    chat_main_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tvMyIp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""/>
        </LinearLayout>
    
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    
        <Button
            android:id="@+id/btnSendMsg"
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:text="send"
            android:layout_weight="0" />
    
        <EditText
            android:id="@+id/etInputMesage"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
    
    
    </LinearLayout>
    
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <TextView
            android:id="@+id/tvOutputMessage"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
    
        </TextView>
    </LinearLayout>
    </LinearLayout>
    

    【讨论】:

    • 什么是客户端如何找到它? ActivityMain.ipToConnect
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    相关资源
    最近更新 更多