创建消息传递应用程序(Wifi)

时间:2013-04-12 09:43:48

标签: android wifi chat messaging

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

非常感谢, 奥勒尔。

2 个答案:

答案 0 :(得分:0)

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

  1. 服务器
  2. 客户端
  3. 在WhatsApp Android应用程序的情况下,它是一个与WhatsApp服务器通信的客户端应用程序。

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

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

答案 1 :(得分:0)

使用此:

  

<强> ChatServerSide

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

<强> ChatClientSide

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>