100% found this document useful (1 vote)
159 views

Android Wifi Chat App

This document describes the development of a WiFi chat application for Android smartphones using socket programming. It includes the program code in Java for the backend and XML for the frontend. The Java code implements socket programming to enable communication between a server app and client app over WiFi. The XML code defines the user interface for the server and client apps. The apps allow two Android devices to connect over WiFi and exchange text messages in real-time.

Uploaded by

NaranLogan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
159 views

Android Wifi Chat App

This document describes the development of a WiFi chat application for Android smartphones using socket programming. It includes the program code in Java for the backend and XML for the frontend. The Java code implements socket programming to enable communication between a server app and client app over WiFi. The XML code defines the user interface for the server and client apps. The apps allow two Android devices to connect over WiFi and exchange text messages in real-time.

Uploaded by

NaranLogan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/303737681

Socket Programming WIFI Chat APP For Android Smartphone

Research · June 2016


DOI: 10.13140/RG.2.1.3692.2483

CITATION READS

1 30,541

1 author:

Abby P Joby
National Institute of Technology Calicut
10 PUBLICATIONS   7 CITATIONS   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Visible Light Communication Using OOK View project

All content following this page was uploaded by Abby P Joby on 02 June 2016.

The user has requested enhancement of the downloaded file.


SOCKET PROGRAMMING
W I F I C H AT A P P F O R
ANDROID SMARTPHONE
Abby P Joby
B130373EC

June 2, 2016

contents
1 Introduction 2
2 Program code 2
2.1 Java Code - Back end . . . . . . . . . . . . . . . . . . . . 2
2.1.1 Server - socket program . . . . . . . . . . . . . . 4
2.1.2 Client socket program . . . . . . . . . . . . . . . 5
2.2 XML Code - front end . . . . . . . . . . . . . . . . . . . 6
2.2.1 Server XML code . . . . . . . . . . . . . . . . . . 6
2.2.2 Client XML code . . . . . . . . . . . . . . . . . . 8
2.3 Putting It Together . . . . . . . . . . . . . . . . . . . . . 10
2.3.1 Java code for the Server Program . . . . . . . . . 10
2.3.2 Java code for the Client Program . . . . . . . . . 13
3 App in action 16
4 Future possibilities 17

list of figures
Figure 1 The Android Studio IDE . . . . . . . . . . . . 2
Figure 2 XML design window . . . . . . . . . . . . . . . 6
Figure 3 Server GUI corresponding to above code . . . 7
Figure 4 Client GUI corresponding to above code . . . . 9
Figure 5 Server app . . . . . . . . . . . . . . . . . . . . . 16
Figure 6 Client app . . . . . . . . . . . . . . . . . . . . . 16
Figure 7 Server shows status . . . . . . . . . . . . . . . . 16
Figure 8 Chat history in client . . . . . . . . . . . . . . . 16

1
introduction 2

1 introduction
In this project, we wish to develop and android application that en-
ables two users to transmit and receive text via WiFi through socket
programming. We have chosen to implement this project on android
smart-phones. The primary programming language used in develop-
ing android apps is Java. All the back end functions and the socket
programming is implemented in Java. The user interface ie front end
is implemented using XML (Extensible Markup Language) and both
the back end and front end are connected together in the Java pro-
gram. We have used the Android Studio IDE (similar to eclipse IDE)
to program the app.

Figure 1: The Android Studio IDE

2 program code
2.1 Java Code - Back end

Every android app is divided into three sections. These three sections
interact with each other through the code to complete the entire app.

• Java code

• XML code

• Android manifest

First let’s look at the Java code. For this project, we had to create
two applications one for the server and another for the client. Both
these apps were running on two different smart-phones. The Java
code of most android apps start with a method called onCreate().
This method defines the initial setup of all the variables and the vari-
ous elements in the application. We can use this section to setup the
program code 3

buttons and define what will happen when the button is pressed. It is
also used to link the element of the front end with the back end. For
eg, the graphic front end element Button is linked to the Java code
through this method. Similarly other elements are also linked.

protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
String ip =
Formatter.formatIpAddress(wmanager.getConnectionInfo().getIpAddress());
smessage = (EditText) findViewById(R.id.smessage);
chat = (TextView) findViewById(R.id.chat);
display_status = (TextView)
findViewById(R.id.display_status);
display_status.setText("Server hosted on " + ip);
Thread serverThread = new Thread(new serverThread());
serverThread.start();
button_sent = (Button) findViewById(R.id.button_sent);
button_sent.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
}

The above is the onCreate() method used in the server application.


A similar method is used in the Client application also. The server
application will display its IP address to which the client can connect.
The port number has been predefined as 10000. Both the applications
run two threads. One is used to scan for incoming messages and the
other is used to send messages.
program code 4

2.1.1 Server - socket program


A socket is an endpoint of a two-way communication link between
two programs running on the network. Socket is bound to a port
number. There are basically 5 steps to create a server program in Java.
Since android apps are developed using Java, the same procedures
apply here also.

• Open server socket

• Wait for client request

• Create I/O stream for communication

• Perform communication

• Close socket

A server program creates a specific type of socket that is used to


listen for client requests (server socket). In the case of a connection
request, the program creates a new socket through which it will ex-
change data with the client using input and output streams. The
socket abstraction is very similar to the file concept: developers have
to open a socket, perform I/O, and close it.
// first open a socket in the server
ServerSocket serverSocket = new ServerSocket(port_number);

// next, wait for the client to connect


Socket client = server.accept();

// create I/O streams for communication


DataInputStream is;
DataOutputStream os;
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());

// perform communication
// To receive from client:
String line = is.readLine();

// To send to client:
os.writeBytes();

// close the client socket


client.close();

We have implemented the Server program with two threads. One


thread is called inside the onCreate method and it continuously mon-
itors the input stream for incoming message. The second thread runs
whenever the button is pressed. This is used to write data to the
output stream.
program code 5

2.1.2 Client socket program


The steps involve in creating a client program is very similar to that
of the server program.

• Open socket

• Create I/O stream for communication

• Perform communication

• Close socket

// first open a socket in the server


Socket socket = new Socket(server_ip , port_number);

// create I/O streams for communication


DataInputStream is;
DataOutputStream os;
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());

// perform communication
// To receive from client:
String line = is.readLine();

// To send to client:
os.writeBytes();

// close the client socket


socket.close();
program code 6

2.2 XML Code - front end

The front end of the application was designed in Android Studio IDE
using XML (Extensible Markup Language). The Server and client
apps are designed in different manners. The server application has
just one button and one text field to input text. The client application
has two buttons one to facilitate the connection and one to sent mes-
sages. It also has two text fields, one to input the IP address of the
server and another to input the message to be sent.

Figure 2: XML design window

2.2.1 Server XML code

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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: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="com.example.abby.server.ServerActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Status"
android:id="@+id/display_status"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
program code 7

android:text=">"
android:textSize="30dp"
android:id="@+id/button_sent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/smessage"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/button_sent"
android:layout_toStartOf="@+id/button_sent" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/chat"
android:layout_below="@+id/display_status"
android:layout_marginTop="31dp"
android:layout_above="@+id/button_sent"
android:layout_alignRight="@+id/button_sent"
android:layout_alignEnd="@+id/button_sent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

Figure 3: Server GUI corresponding to above code


program code 8

2.2.2 Client XML code

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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: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="com.example.abby.client.ClientActivity">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/server_ip"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/connect_phones"
android:layout_toStartOf="@+id/connect_phones" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect"
android:id="@+id/connect_phones"
android:layout_alignBottom="@+id/server_ip"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="@+id/sent_button"
android:layout_alignStart="@+id/sent_button" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/smessage"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="enter text to sent"
android:layout_toLeftOf="@+id/sent_button"
android:layout_toStartOf="@+id/sent_button" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=">"
android:textSize="30dp"
android:id="@+id/sent_button"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
program code 9

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:id="@+id/chat"
android:layout_centerHorizontal="true"
android:layout_below="@+id/server_ip"
android:layout_above="@+id/sent_button" />

</RelativeLayout>

Figure 4: Client GUI corresponding to above code


program code 10

2.3 Putting It Together

2.3.1 Java code for the Server Program

package com.example.abby.server;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerActivity extends AppCompatActivity {

Button button_sent;
EditText smessage;
TextView chat,display_status;
String str,msg="";
int serverport = 10000;
ServerSocket serverSocket;
Socket client;
Handler handler = new Handler();
WifiManager wmanager;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);

wmanager = (WifiManager) getSystemService(WIFI_SERVICE);


String ip =
Formatter.formatIpAddress(wmanager.getConnectionInfo().getIpAddress());

smessage = (EditText) findViewById(R.id.smessage);


chat = (TextView) findViewById(R.id.chat);
display_status = (TextView)
findViewById(R.id.display_status);
display_status.setText("Server hosted on " + ip);

Thread serverThread = new Thread(new serverThread());


serverThread.start();

button_sent = (Button) findViewById(R.id.button_sent);


program code 11

button_sent.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
}

class sentMessage implements Runnable


{
@Override
public void run()
{
try
{
Socket client = serverSocket.accept();
DataOutputStream os = new
DataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
msg = msg + "\n Server : " + str;
handler.post(new Runnable()
{
@Override
public void run()
{
chat.setText(msg);
}
});
os.writeBytes(str);
os.flush();
os.close();
client.close();
}
catch(IOException e)
{

}
}

public class serverThread implements Runnable


{
@Override
public void run()
{
try
{
while(true)
program code 12

{
serverSocket = new ServerSocket(serverport);
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
display_status.setText("Connected");
}
});

/*******************************************
setup i/p streams
******************************************/

DataInputStream in = new
DataInputStream(client.getInputStream());
String line = null;
while((line = in.readLine()) != null)
{
msg = msg + "\n Client : " + line;
handler.post(new Runnable()
{
@Override
public void run()
{
chat.setText(msg);
}
});
}
in.close();
client.close();
Thread.sleep(100);
}
}
catch (Exception e)
{

}
}
}

}
program code 13

2.3.2 Java code for the Client Program

package com.example.abby.client;

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 java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class ClientActivity extends Activity {

EditText serverIp,smessage;
TextView chat;
Button connectPhones,sent;
String serverIpAddress = "",msg = "",str;
Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
chat = (TextView) findViewById(R.id.chat);
serverIp = (EditText) findViewById(R.id.server_ip);
smessage = (EditText) findViewById(R.id.smessage);
sent = (Button) findViewById(R.id.sent_button);
sent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals(""))
{
Thread clientThread = new Thread(new
ClientThread());
clientThread.start();
program code 14

}
}
});
}

class sentMessage implements Runnable


{
@Override
public void run()
{
try
{
InetAddress serverAddr =
InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, 10000); //
create client socket
DataOutputStream os = new
DataOutputStream(socket.getOutputStream());
str = smessage.getText().toString();
str = str + "\n";
msg = msg + "Client : " + str;
handler.post(new Runnable() {
@Override
public void run() {
chat.setText(msg);
}
});
os.writeBytes(str);
os.flush();
os.close();
socket.close();
}
catch(IOException e)
{

}
}

public class ClientThread implements Runnable


{
public void run()
{
try
{

while(true)
{
InetAddress serverAddr =
InetAddress.getByName(serverIpAddress);
program code 15

Socket socket = new Socket(serverAddr, 10000); //


create client socket
/*******************************************
setup i/p streams
******************************************/
DataInputStream in = new
DataInputStream(socket.getInputStream());
String line = null;
while ((line = in.readLine()) != null)
{
msg = msg + "Server : " + line + "\n";
handler.post(new Runnable()
{
@Override
public void run()
{
chat.setText(msg);
}
});
}
in.close();
socket.close();
Thread.sleep(100);
}
}
catch (Exception e)
{}
}
}
}
app in action 16

3 app in action
First, we ensure that both the smart-phones are connected to the same
WiFi network. Next open the client and server apps on different
phones. The server app will show its own IP address. This IP ad-
dress is given to the client app. On clicking the connect button, a
connection is established between the client and Server and we are
now ready to transfer information. The below pictures describe the
complete process in work.

Figure 5: Server app Figure 6: Client app

Once the IP address shown in the server app is entered into the
client app, click on the connect button.

Figure 7: Server shows status Figure 8: Chat history in client

Once the connection is established, we can move on to the task of


sending data. The user can input text in the provide space and click
on the button sent. The message will be updated in the chat history
and all the messages are displayed in the screen.
future possibilities 17

4 future possibilities
This basic application could be later extended to facilitate a wider
network. Thus we can conclude that this application would form
the base of some of the popular applications such as Whatsapp and
Snapchat. We could also use this method to establish communication
between wifi enabled sensor networks and an android smartphone
thereby facilitating the Internet Of Things.

View publication stats

You might also like