Implement Unproblematic Android Chat Application, Server Side.

Posted on

It’s a uncomplicated instance of Chat app running on Android devices, both server in addition to clients. One device run AndroidChatServer to human face connecter from clients, other devices run AndroidChatClient to connect to the server. Any AndroidChatClient tin give notice shipping message to server, thence server broadcast to all clients.


Here is the code inward Server side, Client side tin give notice live flora inward adjacent post, “Simple Android Chat Application, customer side
.
MainActivity.java

package com.example.androidchatserver;  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;  import android.support.v7.app.ActionBarActivity; import android.widget.TextView; import android.widget.Toast; import android.os.Bundle;  world flat MainActivity extends ActionBarActivity {   static lastly int SocketServerPORT = 8080;   TextView infoIp, infoPort, chatMsg;   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);    infoIp.setText(getIpAddress());    userList = novel ArrayList<ChatClient>();      ChatServerThread chatServerThread = novel ChatServerThread();   chatServerThread.start();  }   @Override  protected void onDestroy() {   super.onDestroy();    if (serverSocket != null) {    endeavour {     serverSocket.close();    } select handgrip of (IOException e) {     // TODO Auto-generated select handgrip of block     e.printStackTrace();    }   }  }   private flat ChatServerThread extends Thread {    @Override   world void run() {    Socket socket = null;     endeavour {     serverSocket = novel ServerSocket(SocketServerPORT);     MainActivity.this.runOnUiThread(new Runnable() {       @Override      world void run() {       infoPort.setText("I'm waiting here: "         + serverSocket.getLocalPort());      }     });          piece (true) {      socket = serverSocket.accept();      ChatClient customer = novel ChatClient();      userList.add(client);      ConnectThread connectThread = novel ConnectThread(client, socket);      connectThread.start();     }     } select handgrip of (IOException e) {     e.printStackTrace();    } finally {     if (socket != null) {      endeavour {       socket.close();      } select handgrip of (IOException e) {       // TODO Auto-generated select handgrip of block       e.printStackTrace();      }     }    }    }   }    private flat 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   world void run() {    DataInputStream dataInputStream = null;    DataOutputStream dataOutputStream = null;        endeavour {     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      world void run() {       chatMsg.setText(msgLog);      }     });          dataOutputStream.writeUTF("Welcome " + n + "\n");     dataOutputStream.flush();          broadcastMsg(n + " bring together our chat.\n");          piece (true) {      if (dataInputStream.available() > 0) {       String newMsg = dataInputStream.readUTF();                     msgLog += n + ": " + newMsg;       MainActivity.this.runOnUiThread(new Runnable() {         @Override        world void run() {         chatMsg.setText(msgLog);        }       });              broadcastMsg(n + ": " + newMsg);      }            if(!msgToSend.equals("")){       dataOutputStream.writeUTF(msgToSend);       dataOutputStream.flush();       msgToSend = "";      }           }         } select handgrip of (IOException e) {     e.printStackTrace();    } finally {     if (dataInputStream != null) {      endeavour {       dataInputStream.close();      } select handgrip of (IOException e) {       // TODO Auto-generated select handgrip of block       e.printStackTrace();      }     }      if (dataOutputStream != null) {      endeavour {       dataOutputStream.close();      } select handgrip of (IOException e) {       // TODO Auto-generated select handgrip of block       e.printStackTrace();      }     }          userList.remove(connectClient);     MainActivity.this.runOnUiThread(new Runnable() {       @Override      world void run() {       Toast.makeText(MainActivity.this,         connectClient.name + " removed.", Toast.LENGTH_LONG).show();              msgLog += "-- " + connectClient.name + " leaved\n";       MainActivity.this.runOnUiThread(new Runnable() {         @Override        world 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    world void run() {     chatMsg.setText(msgLog);    }   });  }   private String getIpAddress() {   String ip = "";   endeavour {    Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface      .getNetworkInterfaces();    piece (enumNetworkInterfaces.hasMoreElements()) {     NetworkInterface networkInterface = enumNetworkInterfaces       .nextElement();     Enumeration<InetAddress> enumInetAddress = networkInterface       .getInetAddresses();     piece (enumInetAddress.hasMoreElements()) {      InetAddress inetAddress = enumInetAddress.nextElement();       if (inetAddress.isSiteLocalAddress()) {       ip += "SiteLocalAddress: "         + inetAddress.getHostAddress() + "\n";      }      }     }    } select handgrip of (SocketException e) {    // TODO Auto-generated select handgrip of block    e.printStackTrace();    ip += "Something Wrong! " + e.toString() + "\n";   }    provide ip;  }   flat ChatClient {   String name;   Socket socket;   ConnectThread chatThread;     }  } 

/res/layout/activity_main.xml

<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:orientation="vertical"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context=".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" />      <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> 

brand certain Add uses-permission of “android.permission.INTERNET” to AndroidManifest.xml.

s a uncomplicated instance of Chat app running on Android devices Implement uncomplicated Android Chat Application, server side.Download the files.

Related:
Command business version Chat Server.

Next:
– Android Chat example, alongside server sending private message to specify client.


Added@2014-12-06

If yous found “Something Wrong! java.net.SocketException” displayed.

Make certain add permission of “android.permission.INTERNET” inward AndroidManifest.xml. It’s a mutual mistake of missing “android.permission.INTERNET” to cause SocketException.