Android Chat Example, Amongst Server Sending Private Message To Specify Client.

Posted on

Refer to my one-time postal service of Simple Android Chat Application, server side, as well as client side. Function to send sending private message to specify customer is added inward server side.


uses-permission of “android.permission.INTERNET” is needed inward AndroidManifest.xml, for both server as well as client.


Server side:

MainActivity.java

package com.blogspot.android_er.androidchatserver;  import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast;  import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List;  populace shape MainActivity extends AppCompatActivity {      static concluding int SocketServerPORT = 8080;      TextView infoIp, infoPort, chatMsg;     Spinner spUsers;     ArrayAdapter<ChatClient> spUsersAdapter;     Button btnSentTo;      String msgLog = "";      List<ChatClient> userList;      ServerSocket serverSocket;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         infoIp = (TextView) findViewById(R.id.infoip);         infoPort = (TextView) findViewById(R.id.infoport);         chatMsg = (TextView) findViewById(R.id.chatmsg);          spUsers = (Spinner) findViewById(R.id.spusers);         userList = novel ArrayList<ChatClient>();         spUsersAdapter = novel ArrayAdapter<ChatClient>(                 MainActivity.this, android.R.layout.simple_spinner_item, userList);         spUsersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);         spUsers.setAdapter(spUsersAdapter);          btnSentTo = (Button)findViewById(R.id.sentto);         btnSentTo.setOnClickListener(btnSentToOnClickListener);          infoIp.setText(getIpAddress());          ChatServerThread chatServerThread = novel ChatServerThread();         chatServerThread.start();     }      View.OnClickListener btnSentToOnClickListener = novel View.OnClickListener() {         @Override         populace void onClick(View v) {             ChatClient customer = (ChatClient)spUsers.getSelectedItem();             if(client != null){                 String dummyMsg = "Dummy message from server.\n";                 client.chatThread.sendMsg(dummyMsg);                 msgLog += "- Dummy message to " + client.name + "\n";                 chatMsg.setText(msgLog);              }else{                 Toast.makeText(MainActivity.this, "No user connected", Toast.LENGTH_LONG).show();             }         }     };      @Override     protected void onDestroy() {         super.onDestroy();          if (serverSocket != null) {             essay {                 serverSocket.close();             } choose handgrip of (IOException e) {                 // TODO Auto-generated choose handgrip of block                 e.printStackTrace();             }         }     }      private shape ChatServerThread extends Thread {          @Override         populace void run() {             Socket socket = null;              essay {                 serverSocket = novel ServerSocket(SocketServerPORT);                 MainActivity.this.runOnUiThread(new Runnable() {                      @Override                     populace void run() {                         infoPort.setText("I'm waiting here: "                                 + serverSocket.getLocalPort());                     }                 });                  spell (true) {                     socket = serverSocket.accept();                     ChatClient customer = novel ChatClient();                     userList.add(client);                     ConnectThread connectThread = novel ConnectThread(client, socket);                     connectThread.start();                      runOnUiThread(new Runnable() {                         @Override                         populace void run() {                             spUsersAdapter.notifyDataSetChanged();                         }                     });                 }              } choose handgrip of (IOException e) {                 e.printStackTrace();             } in conclusion {                 if (socket != null) {                     essay {                         socket.close();                     } choose handgrip of (IOException e) {                         // TODO Auto-generated choose handgrip of block                         e.printStackTrace();                     }                 }             }          }      }      private shape ConnectThread extends Thread {          Socket socket;         ChatClient connectClient;         String msgToSend = "";          ConnectThread(ChatClient client, Socket socket){             connectClient = client;             this.socket= socket;             client.socket = socket;             client.chatThread = this;         }          @Override         populace void run() {             DataInputStream dataInputStream = null;             DataOutputStream dataOutputStream = null;              essay {                 dataInputStream = novel DataInputStream(socket.getInputStream());                 dataOutputStream = novel DataOutputStream(socket.getOutputStream());                  String n = dataInputStream.readUTF();                  connectClient.name = n;                  msgLog += connectClient.name + " connected@" +                         connectClient.socket.getInetAddress() +                         ":" + connectClient.socket.getPort() + "\n";                 MainActivity.this.runOnUiThread(new Runnable() {                      @Override                     populace void run() {                         chatMsg.setText(msgLog);                     }                 });                  dataOutputStream.writeUTF("Welcome " + n + "\n");                 dataOutputStream.flush();                  broadcastMsg(n + " bring together our chat.\n");                  spell (true) {                     if (dataInputStream.available() > 0) {                         String newMsg = dataInputStream.readUTF();                           msgLog += n + ": " + newMsg;                         MainActivity.this.runOnUiThread(new Runnable() {                              @Override                             populace void run() {                                 chatMsg.setText(msgLog);                             }                         });                          broadcastMsg(n + ": " + newMsg);                     }                      if(!msgToSend.equals("")){                         dataOutputStream.writeUTF(msgToSend);                         dataOutputStream.flush();                         msgToSend = "";                     }                  }              } choose handgrip of (IOException e) {                 e.printStackTrace();             } in conclusion {                 if (dataInputStream != null) {                     essay {                         dataInputStream.close();                     } choose handgrip of (IOException e) {                         // TODO Auto-generated choose handgrip of block                         e.printStackTrace();                     }                 }                  if (dataOutputStream != null) {                     essay {                         dataOutputStream.close();                     } choose handgrip of (IOException e) {                         // TODO Auto-generated choose handgrip of block                         e.printStackTrace();                     }                 }                  userList.remove(connectClient);                  MainActivity.this.runOnUiThread(new Runnable() {                      @Override                     populace void run() {                         spUsersAdapter.notifyDataSetChanged();                         Toast.makeText(MainActivity.this,                                 connectClient.name + " removed.", Toast.LENGTH_LONG).show();                          msgLog += "-- " + connectClient.name + " leaved\n";                         MainActivity.this.runOnUiThread(new Runnable() {                              @Override                             populace void run() {                                 chatMsg.setText(msgLog);                             }                         });                          broadcastMsg("-- " + connectClient.name + " leaved\n");                     }                 });             }          }          private void sendMsg(String msg){             msgToSend = msg;         }      }      private void broadcastMsg(String msg){         for(int i=0; i<userList.size(); i++){             userList.get(i).chatThread.sendMsg(msg);             msgLog += "- shipping to " + userList.get(i).name + "\n";         }          MainActivity.this.runOnUiThread(new Runnable() {              @Override             populace void run() {                 chatMsg.setText(msgLog);             }         });     }      private String getIpAddress() {         String ip = "";         essay {             Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface                     .getNetworkInterfaces();             spell (enumNetworkInterfaces.hasMoreElements()) {                 NetworkInterface networkInterface = enumNetworkInterfaces                         .nextElement();                 Enumeration<InetAddress> enumInetAddress = networkInterface                         .getInetAddresses();                 spell (enumInetAddress.hasMoreElements()) {                     InetAddress inetAddress = enumInetAddress.nextElement();                      if (inetAddress.isSiteLocalAddress()) {                         ip += "SiteLocalAddress: "                                 + inetAddress.getHostAddress() + "\n";                     }                  }              }          } choose handgrip of (SocketException e) {             // TODO Auto-generated choose handgrip of block             e.printStackTrace();             ip += "Something Wrong! " + e.toString() + "\n";         }          provide ip;     }      shape ChatClient {         String name;         Socket socket;         ConnectThread chatThread;          @Override         populace String toString() {             provide advert + ": " + socket.getInetAddress().getHostAddress();         }     } }  

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:padding="16dp"     android:orientation="vertical"     tools:context="com.blogspot.android_er.androidchatserver.MainActivity">      <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:autoLink="web"         android:text="https://rootandroid.org//"         android:textStyle="bold" />      <TextView         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Char Server"         android:textStyle="bold" />      <TextView         android:id="@+id/infoport"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textStyle="italic" />      <TextView         android:id="@+id/infoip"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textStyle="italic" />      <Spinner         android:id="@+id/spusers"         android:layout_width="match_parent"         android:layout_height="wrap_content"/>      <Button         android:id="@+id/sentto"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Sent msg to private user"/>      <ScrollView         android:layout_width="match_parent"         android:layout_height="match_parent" >          <TextView             android:id="@+id/chatmsg"             android:layout_width="wrap_content"             android:layout_height="wrap_content" />     </ScrollView> </LinearLayout>  

sending private message to specify customer is added inward server side Android Chat example, alongside server sending private message to specify client.Download the server side files (Android Studio Format) .


Client side same every bit inward the postal service “Simple Android Chat Application, customer side” inward Android Studio form.

sending private message to specify customer is added inward server side Android Chat example, alongside server sending private message to specify client.Download the customer side files (Android Studio Format) .