We have seen a large number of applications come up in the recent past, to help us connect with each other across different mediums, like Hike, Whatsapp, Viber etc. You would be surprised to learn that its rather quite easy to develop one yourself. I thought providing an insight into developing such an application would be helpful for you guys.

Today we are going to learn how to build a simple group chat app using sockets. I won’t say this is the only way to build a chat app, but it is the quick & easiest way to build one. The best and efficient way would be using the push notifications instead of sockets.

android building chat app using java sockets

Overall we are going to build three components in this article. The first and important component is the socket server. The socket server plays a major role like handling the socket client connections, passing the messages between clients. Second component is the web app where you can join the chat conversation from a browser. Finally the android app. The main advantage of this app is, you can chat between web – web, web – android or android – android.

As this article seems pretty much lengthy, I am dividing the tutorial into two parts. In this first part, all the basic setup and building the web app is covered. In the 2nd Part, building the actual android app is covered.

Below are the final outcomes from this tutorial.

android building chat app like whatsapp

How the App Works Over Sockets?

If you are coming across the ‘sockets’ for the first time, the wikipedia page give you basic knowledge about socket communication. Below you can find a brief info about how our app works.

1. First we’ll have a socket server running. When the android app or web app connects to socket server, the server opens a TCP connection between server and client. The server is capable of opening concurrent connections when there are multiple clients.

2. When a socket connection is established few callback methods like onOpen, onMessage, onExit will be triggered on the both the ends (on server side and client side). There will be another method available to send message from client to server, or vice versa.

3. JSON strings will be exchanged between server and client as a communication medium. Each JSON contains a node called flag to identify the purpose of JSON message. Below is example of JSON when a client joined the conversation that contains the client name, session id and number of people online.

{
    "message": " joined conversation!",
    "flag": "new",
    "sessionId": "4",
    "name": "Ravi Tamada",
    "onlineCount": 6
}

4. Whenever a JSON message received on client side, the JSON will be parsed and appropriate action will be taken.

I hope the above information gave enough knowledge over the app. Now we can move forward and start building one by one component.


1. Eclipse adding J2EE & Tomcat 7 Support

The eclipse IDE that comes along with android SDK, doesn’t have J2EE and Tomcat server support. So we have to add J2EE and tomcat extensions. Another option would be downloading another eclipse that supports J2EE, but I would like use the eclipse that supports both android and j2ee instead of two different IDEs.

1. Download apache tomcat 7 from tomcat website. (You can download it from this direct link). Once downloaded, extract it in some location.

2. In Eclipse go to Help ⇒ Install New Software. Click on Work with drop down and select Juno – http://download.eclipse.org/releases/juno. (You might need to select the appropriate eclipse release depending upon your eclipse flavour)

3. Expand Web, XML, Java EE and OSGi Enterprise Development and select below extensions and proceed with installation.
   > Eclipse Java EE Developer Tools
   > JST Server Adapters
   > JST Server Adapters Extensions

4. Once the extensions are installed, Eclipse will prompt you to restart. When the eclipse re-opened, we need to create a server first. Goto Windows ⇒ Show View ⇒ Server ⇒ Servers.

5. In servers tab, click on new server wizard and select Apache ⇒ Tomcat v7.0 Server. Give server name, browse and select the tomcat home directory which we downloaded previously.

Check out the below video if you not very clear with the above steps.


2. Finding Your PC IP Address

As we need to test this app on multiple devices (it can be a mobile, PC or a laptop) in a wifi network, we need to know the IP address of the PC where the socket server project running. So instead of using localhost, we need to use the ip address in the url. In order to get the ip address of your machine, execute below commands in terminal.

On Windows

ipconfig
windows-os-getting-ip-address

On Mac

ifconfig
mac os getting system ip address

Note: The ip address of your machine might changes whenever you disconnected from wifi or a new device added to wifi network. So make sure that you are using the correct ip address every time you test the app.

Once the Eclipse Tomcat setup is ready and you know the IP address, you are good to go with socket server development. Building the socket server is very easy. The socket server we are going to build won’t take more than two class files.

3. Building the Socket Server

1. In Eclipse create a new Dynamic Web Project by navigating to File ⇒ New ⇒ Other ⇒ Web ⇒ Dynamic Web Project. Give the project name and select the Target runtime as Tomcat 7. I gave my project name as WebMobileGroupChatServer.

Once the project is created, it contains below directory structure.

j2ee web dynamic project directory structure

2. Right click on src ⇒ New ⇒ Package and give the package name. I gave my package name as info.androidhive.webmobilegroupchat.

3. Now download google-collections-0.8.jar, javaee-api-7.0.jar, json-org.jar files and paste them in project’s WebContent ⇒ WEB-INF ⇒ lib folder.

4. Create a new class named JSONUtils.java under project’s src package folder. This class contains methods to generate JSON strings those are required to have the communication b/w socket server and clients.

In the below code, if you observer each json contains flag node which tell the clients the purpose of JSON message. On the client side we have to take appropriate action considering the flag value.

Basically the flag contains four values.

self = This JSON contains the session information of that particular client. This will be the first json a client receives when it opens a sockets connection.

new = This JSON broadcasted to every client informing about the new client that is connected to socket server.

message = This contains the message sent by a client to server. Hence it will broadcasted to every client.

exit = The JSON informs every client about the client that is disconnected from the socket server.

package info.androidhive.webmobilegroupchat;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONUtils {

	// flags to identify the kind of json response on client side
	private static final String FLAG_SELF = "self", FLAG_NEW = "new",
			FLAG_MESSAGE = "message", FLAG_EXIT = "exit";

	public JSONUtils() {
	}

	/**
	 * Json when client needs it's own session details
	 * */
	public String getClientDetailsJson(String sessionId, String message) {
		String json = null;

		try {
			JSONObject jObj = new JSONObject();
			jObj.put("flag", FLAG_SELF);
			jObj.put("sessionId", sessionId);
			jObj.put("message", message);

			json = jObj.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return json;
	}

	/**
	 * Json to notify all the clients about new person joined
	 * */
	public String getNewClientJson(String sessionId, String name,
			String message, int onlineCount) {
		String json = null;

		try {
			JSONObject jObj = new JSONObject();
			jObj.put("flag", FLAG_NEW);
			jObj.put("name", name);
			jObj.put("sessionId", sessionId);
			jObj.put("message", message);
			jObj.put("onlineCount", onlineCount);

			json = jObj.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return json;
	}

	/**
	 * Json when the client exits the socket connection
	 * */
	public String getClientExitJson(String sessionId, String name,
			String message, int onlineCount) {
		String json = null;

		try {
			JSONObject jObj = new JSONObject();
			jObj.put("flag", FLAG_EXIT);
			jObj.put("name", name);
			jObj.put("sessionId", sessionId);
			jObj.put("message", message);
			jObj.put("onlineCount", onlineCount);

			json = jObj.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return json;
	}

	/**
	 * JSON when message needs to be sent to all the clients
	 * */
	public String getSendAllMessageJson(String sessionId, String fromName,
			String message) {
		String json = null;

		try {
			JSONObject jObj = new JSONObject();
			jObj.put("flag", FLAG_MESSAGE);
			jObj.put("sessionId", sessionId);
			jObj.put("name", fromName);
			jObj.put("message", message);

			json = jObj.toString();

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return json;
	}
}

5. Create another class named SocketServer.java and add the below code. This is the where we implement actual socket server.

This class mainly contains four callback methods.

onOpen() – This method is called when a new socket client connects.
onMessage() – This method is called when a new message received from the client.
onClose() – This method is called when a socket client disconnected from the server.
sendMessageToAll() – This method is used to broadcast a message to all socket clients.

package info.androidhive.webmobilegroupchat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.common.collect.Maps;

@ServerEndpoint("/chat")
public class SocketServer {

	// set to store all the live sessions
	private static final Set<Session> sessions = Collections
			.synchronizedSet(new HashSet<Session>());

	// Mapping between session and person name
	private static final HashMap<String, String> nameSessionPair = new HashMap<String, String>();

	private JSONUtils jsonUtils = new JSONUtils();

	// Getting query params
	public static Map<String, String> getQueryMap(String query) {
		Map<String, String> map = Maps.newHashMap();
		if (query != null) {
			String[] params = query.split("&");
			for (String param : params) {
				String[] nameval = param.split("=");
				map.put(nameval[0], nameval[1]);
			}
		}
		return map;
	}

	/**
	 * Called when a socket connection opened
	 * */
	@OnOpen
	public void onOpen(Session session) {

		System.out.println(session.getId() + " has opened a connection");

		Map<String, String> queryParams = getQueryMap(session.getQueryString());

		String name = "";

		if (queryParams.containsKey("name")) {

			// Getting client name via query param
			name = queryParams.get("name");
			try {
				name = URLDecoder.decode(name, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			// Mapping client name and session id
			nameSessionPair.put(session.getId(), name);
		}

		// Adding session to session list
		sessions.add(session);

		try {
			// Sending session id to the client that just connected
			session.getBasicRemote().sendText(
					jsonUtils.getClientDetailsJson(session.getId(),
							"Your session details"));
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Notifying all the clients about new person joined
		sendMessageToAll(session.getId(), name, " joined conversation!", true,
				false);

	}

	/**
	 * method called when new message received from any client
	 * 
	 * @param message
	 *            JSON message from client
	 * */
	@OnMessage
	public void onMessage(String message, Session session) {

		System.out.println("Message from " + session.getId() + ": " + message);

		String msg = null;

		// Parsing the json and getting message
		try {
			JSONObject jObj = new JSONObject(message);
			msg = jObj.getString("message");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// Sending the message to all clients
		sendMessageToAll(session.getId(), nameSessionPair.get(session.getId()),
				msg, false, false);
	}

	/**
	 * Method called when a connection is closed
	 * */
	@OnClose
	public void onClose(Session session) {

		System.out.println("Session " + session.getId() + " has ended");

		// Getting the client name that exited
		String name = nameSessionPair.get(session.getId());

		// removing the session from sessions list
		sessions.remove(session);

		// Notifying all the clients about person exit
		sendMessageToAll(session.getId(), name, " left conversation!", false,
				true);

	}

	/**
	 * Method to send message to all clients
	 * 
	 * @param sessionId
	 * @param message
	 *            message to be sent to clients
	 * @param isNewClient
	 *            flag to identify that message is about new person joined
	 * @param isExit
	 *            flag to identify that a person left the conversation
	 * */
	private void sendMessageToAll(String sessionId, String name,
			String message, boolean isNewClient, boolean isExit) {

		// Looping through all the sessions and sending the message individually
		for (Session s : sessions) {
			String json = null;

			// Checking if the message is about new client joined
			if (isNewClient) {
				json = jsonUtils.getNewClientJson(sessionId, name, message,
						sessions.size());

			} else if (isExit) {
				// Checking if the person left the conversation
				json = jsonUtils.getClientExitJson(sessionId, name, message,
						sessions.size());
			} else {
				// Normal chat conversation message
				json = jsonUtils
						.getSendAllMessageJson(sessionId, name, message);
			}

			try {
				System.out.println("Sending Message To: " + sessionId + ", "
						+ json);

				s.getBasicRemote().sendText(json);
			} catch (IOException e) {
				System.out.println("error in sending. " + s.getId() + ", "
						+ e.getMessage());
				e.printStackTrace();
			}
		}
	}
}

With this we have completed the socket server part. Now quickly we can build a web app to the test the socket server. Again building the web app is very simple. The complete web app can be built using basic web technologies like HTML, CSS & jQuery.

4. Building The Web App (HTML, CSS & jQuery)

To create the web app, we don’t have to create another project. This is the part of same socket server project, so follow the below steps in the same project.

1. Create a file named style.css under WebContent ⇒ WEB-INF folder. This contains the css styles for the web UI.

body {
	padding: 0;
	margin: 0;
}

.body_container {
	width: 1000px;
	margin: 0 auto;
	padding: 0;
}

.clear {
	clear: both;
}

.green {
	color: #8aaf0d;
}

#header {
	margin: 0 auto;
	padding: 50px 0;
	text-align: center;
}

#header h1,#header p.online_count {
	font-family: 'Open Sans', sans-serif;
	font-weight: 300;
}

#header p.online_count {
	font-size: 18px;
	display: none;
}

.box_shadow {
	background: #f3f4f6;
	border: 1px solid #e4e4e4;
	-moz-box-shadow: 0px 0px 2px 1px #e5e5e5;
	-webkit-box-shadow: 0px 0px 2px 1px #e5e5e5;
	box-shadow: 0px 0px 2px 1px #e5e5e5;
}

#prompt_name_container {
	margin: 0 auto;
	width: 350px;
	text-align: center;
}

#prompt_name_container p {
	font-family: 'Open Sans', sans-serif;
	font-weight: 300;
	font-size: 24px;
	color: #5e5e5e;
}

#prompt_name_container #input_name {
	border: 1px solid #dddddd;
	padding: 10px;
	width: 250px;
	display: block;
	margin: 0 auto;
	outline: none;
	font-family: 'Open Sans', sans-serif;
}

#prompt_name_container #btn_join {
	border: none;
	width: 100px;
	display: block;
	outline: none;
	font-family: 'Open Sans', sans-serif;
	color: #fff;
	background: #96be0e;
	font-size: 18px;
	padding: 5px 20px;
	margin: 15px auto;
	cursor: pointer;
}

#message_container {
	display: none;
	width: 500px;
	margin: 0 auto;
	background: #fff;
	padding: 15px 0 0 0;
}

#messages {
	margin: 0;
	padding: 0;
	height: 300px;
	overflow: scroll;
	overflow-x: hidden;
}

#messages li {
	list-style: none;
	font-family: 'Open Sans', sans-serif;
	font-size: 16px;
	padding: 10px 20px;
}

#messages li.new,#messages li.exit {
	font-style: italic;
	color: #bbbbbb;
}

#messages li span.name {
	color: #8aaf0d;
}

#messages li span.red {
	color: #e94e59;
}

#input_message_container {
	margin: 40px 20px 0 20px;
}

#input_message {
	background: #f0f0f0;
	border: none;
	font-size: 20px;
	font-family: 'Open Sans', sans-serif;
	outline: none;
	padding: 10px;
	float: left;
	margin: 0;
	width: 348px;
}

#btn_send {
	float: left;
	margin: 0;
	border: none;
	color: #fff;
	font-family: 'Open Sans', sans-serif;
	background: #96be0e;
	outline: none;
	padding: 10px 20px;
	font-size: 20px;
	cursor: pointer;
}

#btn_close {
	margin: 0;
	border: none;
	color: #fff;
	font-family: 'Open Sans', sans-serif;
	background: #e94e59;
	outline: none;
	padding: 10px 20px;
	font-size: 20px;
	cursor: pointer;
	width: 100%;
	margin: 30px 0 0 0;
}

2. Create another file named main.js and add below javascript. This file contains all the methods required to handle communication between socket server and client. The other things like parsing JSON, appending messages to chat list also taken care in the same file.

// to keep the session id
var sessionId = '';

// name of the client
var name = '';

// socket connection url and port
var socket_url = '192.168.0.102';
var port = '8080';

$(document).ready(function() {

	$("#form_submit, #form_send_message").submit(function(e) {
		e.preventDefault();
		join();
	});
});

var webSocket;

/**
 * Connecting to socket
 */
function join() {
	// Checking person name
	if ($('#input_name').val().trim().length <= 0) {
		alert('Enter your name');
	} else {
		name = $('#input_name').val().trim();

		$('#prompt_name_container').fadeOut(1000, function() {
			// opening socket connection
			openSocket();
		});
	}

	return false;
}

/**
 * Will open the socket connection
 */
function openSocket() {
	// Ensures only one connection is open at a time
	if (webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED) {
		return;
	}

	// Create a new instance of the websocket
	webSocket = new WebSocket("ws://" + socket_url + ":" + port
			+ "/WebMobileGroupChatServer/chat?name=" + name);

	/**
	 * Binds functions to the listeners for the websocket.
	 */
	webSocket.onopen = function(event) {
		$('#message_container').fadeIn();

		if (event.data === undefined)
			return;

	};

	webSocket.onmessage = function(event) {

		// parsing the json data
		parseMessage(event.data);
	};

	webSocket.onclose = function(event) {
		alert('Error! Connection is closed. Try connecting again.');
	};
}

/**
 * Sending the chat message to server
 */
function send() {
	var message = $('#input_message').val();

	if (message.trim().length > 0) {
		sendMessageToServer('message', message);
	} else {
		alert('Please enter message to send!');
	}

}

/**
 * Closing the socket connection
 */
function closeSocket() {
	webSocket.close();

	$('#message_container').fadeOut(600, function() {
		$('#prompt_name_container').fadeIn();
		// clearing the name and session id
		sessionId = '';
		name = '';

		// clear the ul li messages
		$('#messages').html('');
		$('p.online_count').hide();
	});
}

/**
 * Parsing the json message. The type of message is identified by 'flag' node
 * value flag can be self, new, message, exit
 */
function parseMessage(message) {
	var jObj = $.parseJSON(message);

	// if the flag is 'self' message contains the session id
	if (jObj.flag == 'self') {

		sessionId = jObj.sessionId;

	} else if (jObj.flag == 'new') {
		// if the flag is 'new', a client joined the chat room
		var new_name = 'You';

		// number of people online
		var online_count = jObj.onlineCount;

		$('p.online_count').html(
				'Hello, <span class="green">' + name + '</span>. <b>'
						+ online_count + '</b> people online right now')
				.fadeIn();

		if (jObj.sessionId != sessionId) {
			new_name = jObj.name;
		}

		var li = '<li class="new"><span class="name">' + new_name + '</span> '
				+ jObj.message + '</li>';
		$('#messages').append(li);

		$('#input_message').val('');

	} else if (jObj.flag == 'message') {
		// if the json flag is 'message', it means somebody sent the chat
		// message

		var from_name = 'You';

		if (jObj.sessionId != sessionId) {
			from_name = jObj.name;
		}

		var li = '<li><span class="name">' + from_name + '</span> '
				+ jObj.message + '</li>';

		// appending the chat message to list
		appendChatMessage(li);

		$('#input_message').val('');

	} else if (jObj.flag == 'exit') {
		// if the json flag is 'exit', it means somebody left the chat room
		var li = '<li class="exit"><span class="name red">' + jObj.name
				+ '</span> ' + jObj.message + '</li>';

		var online_count = jObj.onlineCount;

		$('p.online_count').html(
				'Hello, <span class="green">' + name + '</span>. <b>'
						+ online_count + '</b> people online right now');

		appendChatMessage(li);
	}
}

/**
 * Appending the chat message to list
 */
function appendChatMessage(li) {
	$('#messages').append(li);

	// scrolling the list to bottom so that new message will be visible
	$('#messages').scrollTop($('#messages').height());
}

/**
 * Sending message to socket server message will be in json format
 */
function sendMessageToServer(flag, message) {
	var json = '{""}';

	// preparing json object
	var myObject = new Object();
	myObject.sessionId = sessionId;
	myObject.message = message;
	myObject.flag = flag;

	// converting json object to json string
	json = JSON.stringify(myObject);

	// sending message to server
	webSocket.send(json);
}

3. Now download jquery-1.11.1.min and the paste the file in WebContent ⇒ WEB-INF.

4. Finally create another file named index.html and add below code.

<!DOCTYPE html>

<html>
<head>
<title>Android, WebSockets Chat App | AndroidHive
	(www.androidhive.info)</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<link
	href='http://fonts.googleapis.com/css?family=Open+Sans:400,600,300,700'
	rel='stylesheet' type='text/css'>
<link href="style.css" type="text/css" rel='stylesheet' />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
	<div class="body_container">

		<div id="header">
			<h1>Android WebSockets Chat Application</h1>
			<p class='online_count'>
				<b>23</b> people online right now
			</p>
		</div>

		<div id="prompt_name_container" class="box_shadow">
			<p>Enter your name</p>
			<form id="form_submit" method="post">
				<input type="text" id="input_name" /> <input type="submit"
					value="JOIN" id="btn_join">
			</form>
		</div>

		<div id="message_container" class="box_shadow">

			<ul id="messages">
			</ul>


			<div id="input_message_container">
				<form id="form_send_message" method="post" action="#">
					<input type="text" id="input_message"
						placeholder="Type your message here..." /> <input type="submit"
						id="btn_send" onclick="send();" value="Send" />
					<div class="clear"></div>
				</form>
			</div>
			<div>

				<input type="button" onclick="closeSocket();"
					value="Leave Chat Room" id="btn_close" />
			</div>

		</div>

	</div>

</body>
</html>

5. Now run the project by Right Click on project ⇒ Run As ⇒ Run on Server. You can see the project running on http://localhost:8080/WebMobileGroupChatServer/

5. Testing The Socket Server (using the web app)

In order to test the socket server using the web app, follow below steps. You can use multiple devices (like desktop PC, Laptop) or just one machine is enough.

1. Make sure that all the machines connected to same wifi router if you are testing the app on multiple machines. If you are testing the app using a single computer, you don’t have to connect to a wifi network.

2. Find the IP address of the machine on which socket server project is running. (Follow the steps mentioned in 2nd point to get the ip address)

3. Replace the ip address in main.js with your machine’s ip address.

var socket_url = '_YOUR_IP_ADDRESS_';

4. Now access your project url in browser. Replace localhost with your machine ip address in the url. My project url is http://192.168.0.104:8080/WebMobileGroupChatServer/. Access same url in another browser software or another machine’s browser to chat with different machines.


Once you are able to chat between multiple clients, we can go forward and build the android app in Android Building Group Chat App using Sockets – Part 2

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Jonathan

    Awesome! I LOVE your tutorials

    • Thanks Jonathan 🙂

      • Athil

        yes ,that’s a greate work thank u Ravi

  • Prathap

    Excellent Work Ravi. Looking for more tuts like this.

  • Sara

    Excellent work Love you man and I have a request can you please help us about some design tutorial using material app design ?

  • Tom Johnson

    What about status bar notifications?

  • Andre

    What about over the internet? I notice this is just over the same wifi

    • I tried searching free socket hosting server, but couldn’t find any. You might need to buy a hosting like digitalocean and do the setup over there.

      • Imthiyas

        what about openshift.com.??

  • mustafa addam

    Hey Ravi Tamada nice tutorial thank you can you soon do that but using apache server i mean with database and php so chat could be use through push notification not socket cause it will really help me in my future projects.

    • Yeah sure. But for that I need to cover few topics first.

      • mustafa addam

        ok no problem waiting for awesome tutorials from you 🙂

      • adam

        hi how can i put this to my website ,for example i wanna use this from ” website.com/chat”

  • Abdullah

    error in jquery-1.11.1.min.js
    “undefined”!=typeof window?window:this

  • ahmad najar

    ihave error conection is closed in 8080 port

  • adam

    hi how can i put this to my website ,for example i wanna use this from ” website.com/chat”

  • KenZira

    Hi, I downloaded your source code. It worked. However, I created my own project and just follow the instructions above. It didn’t work. The problem is “description The requested resource is not available.” which I encountered on the browser.

    • KenZira

      I solved the problem

      • Ranjit

        How you solved it??? I am getting same error…

        • Kelvin

          change the admin and http/1.1 ports then restart your server

  • 25

    Hi. I also downloaded your source code. However i am a beginner with sockets. Im this moment is giving me this error.

    WebSocket connection to ‘ws://%20192.168.1.181:8080/WebMobileGroupChatServer/chat?name=cenz’ failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

    Thanks and great tutorial again;)

    • 25

      Never mind , my bad 😀

      your tutorials are really awesome !!

  • Er Akhtar Raza Ansari

    jquery-1.11.1.min.js file is showing error please help

    • If the error is shown by Eclipse, you can ignore it.

  • Vivek Bansal

    WebSocket connection to ‘ws://192.168.0.2:8080/WebMobileGroupChatServer/chat?name=demo’ failed: Error during WebSocket handshake: Unexpected response code: 404

    This is the error which console is showing. Please help with this.

  • SG

    I am also getting same error as of Vivek Bansal webSocket = new WebSocket(“ws://” + socket_url + “:” + port

    + “/WebMobileGroupChatServer/chat?name=” + name);

  • SG

    I am also getting same error as of Vivek Bansal webSocket = new WebSocket(“ws://” + socket_url + “:” + port

    + “/WebMobileGroupChatServer/chat?name=” + name);

  • TK

    AWESOME tutorial. I think you should have a donate button at least for some appreciation. 🙂

    I managed to set it up but when I enter a name and click join all I see is the title “Android WebSockets Chat Application. ” I cannot see the chat room 🙁 (Running on a mac) Might you know what the issues is?

    • Kelvin

      Hi TK,

      Were you able to solve the chatroom issue?

  • steve

    great tutorial

  • TK

    Hi Guys,

    For all those getting “Unexpected response code: 404” Use Tomcat 7. I realised if you use any other version you will get the 404 error. The server gets the payload but cannot send out a response. I uninstalled previous versions of Tomcat and set Vs as the default. Works like a charm.

    Awesome Tutorial Ravi 🙂

    Enjoy

    • Thanks for your Tip TK 🙂

      • Vishal Bhardwaj

        HI Ravi,,
        I’m too getting the same error.
        I’m using Tomcat ver 7.0 only.
        How to resolve it

    • Vishal Bhardwaj

      I’m too getting the same error.
      I’m using Tomcat ver 7.0 only.
      How to resolve it

  • Ankit

    while testing on same pc with different browser shows error! connection is closed try again

    • Krishnendu Roy

      I have face same error. r u solve this problem?

  • Matriks

    Hi ravi, you rock man..!!!! can you cover with picture attachment pls…

  • Great tutorial, I was trying to create a chat for staff.
    I really like the tutorials on this site.
    Ravi great job.

  • mmy

    Hi Ravi, I have a question, if I use Android Studio instead of Eclipse, how I install new software since there are no “install new software” in Windows tab?

  • Dung

    Thanks tutorial.
    help me.
    I want save data chat.

  • Thomas

    Hi Ravi,

    Is it possible to automatically start the socket server without having to run it via Eclipse? I want to host it on an online server but I am not sure on how to proceed from here. Could you kindly advice?

  • John

    Hello,

    Your every tutorial is nice but can you plzz upload the inappbilling tutorial current many app have in app billing features so it is really good for us thanks keep it up

  • mahdi

    hi , how to make chat between client and client android over web with json and socket?

  • mahdi

    hi , how to make chat between client and client android over web with json and socket?h

  • Ankur

    Hello Ravi, first of all thanks for such a helpfull stuff,
    I just implemented this first part,
    when i user to run the project, it shows:

    HTTP Status 404 – /WebMobileGroupChatServer/

    type Status report

    message /WebMobileGroupChatServer/

    description The requested resource (/WebMobileGroupChatServer/) is
    not available.

    this type of error, i user the updated tomcat v 7.0 also.
    please let me know where i am doing wrong. thanks.

    • Kelvin

      right click your tomcat server on eclipse then click on properties.
      on the dialogwindow click on ‘switch location’ then apply and close.

      Go back to your server and double click it.
      on server locations tab select ‘use Tomcat Installation’
      then save and restart your server

      if that doesnt work you will have to go the extra mile of killing the task listening in on port 8080 and 8005 then change the admin and http ports used by Tomcat on Eclipse

      • Sam

        hey kelvin i tried ur solution, but it still gives me the same error, can u elaborate what you said about “killing the task listening in on port 8080 and 8005″….

    • Veeraj Poojary

      is index.html and its related files within WebMobileGroupChatServer folder ?
      if not, do it and give it a try.

    • Duy

      Put that all files in the top of webcontent folder,not in web-inf

  • Kelvin

    Hi Ravi, Awesome tutorial. Really helpful.

    I was able to do the complete tutorial but when I enter a name and click join the message container does not fadein and all I see is the title “Android WebSockets Chat Application. Might you know what the issues is?

    • Arnav

      I to have the same issue please help !

      • Kelvin

        I have not yet found the solution… will post it when i do

    • Jan

      Same here !

  • rahul

    Hi Ravi,
    Am getting below error after enter the name

    Firefox can’t establish a connection to the server at ws://10.27.96.158:8080/WebMobileGroupChatServer/chat?name=aaa.

    • Make sure that socket server is running and firefox version is supporting websockets.

    • Jan

      Make also sure you are running version of TomCat which contains websocket-api.jar in its lib folder.

  • Yusuf

    Hi Ravi,

    When I try test the socket server it shows this error

    HTTP Status 404 – /WebMobileGroupChatServer/

    type Status report

    message /WebMobileGroupChatServer/

    description The requested resource is not available.

    How can I solve this please

    • Yusuf

      Anyone help pls 🙁

      • MackAttack

        I had the same error, i had index.html, main.js, style.css and the jquery min.js files in the wrong folder, make sure they are in the top level of the web content folder.

    • xXGh0stXx

      Various errors possible, but one could be that Eclipse doesnt generate web.xml by default. Right click on the project -> Java EE Tools -> Generate Deployment Descriptor Stub

  • Cát Khang

    hi Ravi for this tutorial
    Can you help me this >
    When i clicked Join button but i dont see something then . have title is only .
    Please help me . I very interest this tutorial .
    Thanks .

    • Jishma

      Am also facing this same issue. plz help

      • Andrea

        Same issue

    • Jan

      Me too and I have no idea what to do with it !

    • Csaba Pádár

      Me too 🙁

    • Jan

      Problem solved, please use latest TomCat and make sure that it contains websocket-api jars in its lib folder.

      • Bheeshm Pareek

        no its not solve dude i tried latest version and also websocket-api tel me what should i do

    • Duy

      @Cát Khang : Sửa được chưa bạn??

  • congthuc

    very cool, thanks a lot!

  • Salim Alhassan

    Very educative and awesome tutorial. I love it. Please i have added the J2EE and Tomcat support to my eclipse but when i tried to create a new Dynamic Web Project I got this error message–>>

    The selected wizard could not be started.
    Plug-in “org.eclipse.jst.servlet.ui” was unable to instantiate class “org.eclipse.jst.servlet.ui.project.facet.WebProjectWizard”.
    Could not initialize class org.eclipse.jst.j2ee.project.facet.IJ2EEFacetConstants

    Please, i need an assistance. Thank you

  • Sizwe

    ok what i need to know is how do i implement this on my server that is hosted by a website

  • husain

    Hi Ravi Sir nice tutorial .First of all thank you for all the tutorials.I am big fan of you.Can you share the same topic with GCM .It will really help me .plzzzz also post some tutorials which based on sensors & beacone

  • Csaba Pádár

    Hey. Good tutorial! After giving name and clicking join button nothing happens. jquery-1.11.1.min.js file has 1 error, how can I solve that? Anyone, pls!

    • sachit

      Have you find the solution for this problem. I am also getting same.

      • sachit

        I have found the solution and its working fine.

        • Csaba Pádár

          help me

          • sachit

            There is no problem with the js. You can change the mapping of files like create a folder in webcontent with name css and js and put corresponding files into that folders instead of WEB-INF. Also there is no need “javaee-api-7.0.jar” as it is in tomcat 7.0 itself so just delete it from lib folder. Now deploy your app. it should work. Let me know if you still get problem.

          • Thanks 🙂

          • MackAttack

            i have this problem, i click join and nothing happens, the box just fades away

          • MackAttack

            nevermind

          • Anthony Liu

            Hi MackAttack,
            How did you solve the problem?
            Thanks in advance

          • MackAttack

            clear your browser history and retry

          • Yamini

            Have you find the solution for this problem?

          • MackAttack

            @Yamini @Anthony Liu i think you have to clear your browser cache and retry

          • Vicky Garg

            “NetworkError: 404 Not Found – http://192.168.2.136:8081/WebTEstProject

          • Srikanth Munaga

            hi sachit and i followed the suggestions suggested by u the i am facing the same issue when i click on join the box just fades.
            please help me thanks in advance.

          • Yamini

            Did you got the solution of this ?Please help me

          • Sunny020

            Hello

            i am going thru ur article on ur site but got some prob now

            hope u can help me out

            here is the link – http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-2/

            In this i m getting error at few places in WebMobileGroupChat project

            1st i getting error in all three src> .java files

            R cannot be resolved to a variable in

            2nd i get error in MainActivity.java n MessagesListAdapter.java error as The type MainActivity is already defined and MessagesListAdapter cannot be resolved to a type

            Rest all code is error free…

            hope u will help me out soon..

            thnx…

          • harisha

            to sachit
            hello sir.. me too a beginner in this socket prgramming .. the above solution u gave isnt working for me.. i m using eclipse luna with tomcat 8 and even tried with tomcat 7. it s still the same after entering the name and joining the page only gets refresh or reloaded. please help

  • Arshad

    How to install on hosting server. I have my own hosting server how to set up it on it?

    • Adedara Klever Olanrewaju

      Hey Arshad,did u get the solution?

  • Andrea

    Hi, I tried several times, but i got always the same error….HTTP status 404:The requested resource is not available. What can be wrong? I followed your tutorial step by step.

    • ThisIsJimmy

      I realize that this error probably comes up for any number of reasons, but I’m in the same boat as Andrea and would appreciate any insight. I’ve tried the things others (Kelvin and Seph) have posted.
      I’m wondering if it has something to do with the jquery-1.11.1.min step. I wasn’t able to ‘download’ this. Instead, clicking on the link opened a new tab. Copied the contents and pasted in a New File, and gave the file the name jquery-1.11.1.min.js
      Is this where I went wrong?

      • MackAttack

        make sure the files are in the correct folders, i got this error because i had files in the wrong folders

  • seph

    if anyone suffers from this error:

    WebSocket connection to ‘ws://192.168.56.1:8080/WebMobileGroupChatServer/chat?name=sdf’ failed: Error during WebSocket handshake: Unexpected response code: 404)

    this might be the reason:
    on this site ->http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html it says ‘The JSR-356 Java WebSocket 1.1 implementation is only available when Tomcat is running on Java 7 or later.’ therefore any java 6 wont work…i spent a whole day trying to work out why my websocket doesnt work…

  • Gamis

    Nice example of sockets… is amazing how you explain all that 🙂 maybe some day you can use Android Studio 🙂 an developer apps with that SW 🙂

  • kishan dhingani

    i have been install eclipse Java EE Developer Tools,JST Server Adapters,JST Server Adapters Extensions and restart eclipse than after not display server tab in window menu …..

  • Sudheer

    Can some one help me with blocking a particular contact in chat application??

  • Arnav

    Hey What about a One to One chat can we do it with these libraries??I would Love to have that because i have made a connection to a mysql db with the server and made a registration and contacts system.

  • Srikanth Munaga

    hi it is a great tutorial..
    while i am working with it it is fading and not displaying anything please help me

  • Guest

    This is great tutorial.

  • Dép Thị Lào

    this program run good . But how to fix error in jquery-1.11.1.min.js

    • rohit

      rohit

      • Dép Thị Lào

        i did fix it

        • daniel dizzy

          Hi .. How did you fix the jquery-1.11.1.min.js error ??

  • Anukriti

    Hey. nice tutorial! After giving name and clicking join button nothing happens.Would anyone provide a solution for this.

  • 育成 任

    everything is great but the CSS doesn’t work! I don’t know why, please help me.

    • velmurugan

      hi i too faced the same problem.Actually what mistake i did is I created style.css file in

      WEB-INF.i just cut that file and copied it in Web content folder outer to WEB-INF folder.

      then css worked.you can try the same…….

  • Oyewole Samuel Success

    Please, how can i add J2EE & Tomcat 7 Support for android studio

    • wallace

      try and use intellij idea ultimate come prebundled and with android development plugin

  • kalai

    Getting an error if i click on join button like
    Line: 27
    Error: Object doesn’t support this property or method

  • Selva

    Getiing “Error! Connection is closed. Try connecting again.” while clicking on join button

    • oneme

      I’m in the same point

    • kesumu

      Hey, did you change the code in main.js below? The ‘WebMobileGroupChatServer’ should be your own project name if you intent to connect to your own server. I fixed this through this way.

      // Create a new instance of the websocket
      webSocket = new WebSocket(“ws://” + socket_url + “:” + port
      + “/WebMobileGroupChatServer/chat?name=” + name);

      • Khalil Serano

        can you explain how ?

        i get the same error : Error! Connection is closed. Try connecting again.

        • kesumu

          >>Replace localhost with your machine ip address in the url. My project url is
          >>http://192.168.0.104:8080/WebMobileGroupChatServer/.

          I guess chapter 5.4 above can be the reason. Initiate the websocket in main.js file with your own project url.

          example as:

          >>// Create a new instance of the websocket
          >>webSocket = new WebSocket(“ws://” + socket_url + “:” + port
          >>+ “/your_project_name/chat?name=” + name);

          • Khalil Serano

            can you give me your facebook or skype or anything to contact u please ?

          • Khalil Serano

            the same error Error! Connection is closed. Try connecting again

          • Khalil Serano

            also i get problems in socketserver.java

          • Nikhil Kumar

            how did you manage to run at tomcat 7 ? is it not showing error as
            “The server does not support version 3.1 of the J2EE Web module
            specification.” ? i ran on tomcat 8 then and it’s giving “Error!
            Connection is closed. Try connecting again.” error . how you did it on
            tomcat 7 ? didn’t u changed anything in the existing code ?

  • jay

    Love u gr8 WORK

  • Alok Kumar

    i hv done this..code of chat server..
    but problem, it is not working when i m running it on two machine..
    it is running on only one machine on which server going on..
    when i access this on other machine only app page opening but no other client in joining when i enter the name..and the i click join it becomes blank ..on other machine..
    over all conversation is not working b/w two machine..it is working on one machine among different browser….
    plz tell me ..how to do it..

    • Are the two machines connected by wifi or lan. You need to specify the socket url as the ip address as lan ip address if connected by lan and similarly for wifi.

      • Alok Kumar

        First sorry for the late reply ,,
        yaa same thing i have done but when i try to start conversation between two machines then conversation does not start .,i think it is an application issue

    • Nikhil Kumar

      listen. i need ur help. please tell me did u use tomcat 7 server ? really ? u didn’t get any error ? m not able to run even on single computer. everthing worked fine or you had to do some changes to the existing code?

      • surya

        Hai Niklil, i have the same prob that the webpage fades away… I couldn’t find a way to get rid of it, pls help me out this….

      • Alok Kumar

        yaa i used tomcat server and did not face any problem., and sorry for late reply

  • Hanan Lipskin

    if some will is having any issue with that code you contact me on skype hananlipskin and i will help you out 🙂
    Ravi thank you so much for your time

  • zoltaare

    Nice!!! Can you give an example or an overview on how to implement file transfer? Thank You. 🙂

  • Rahul

    How to this in my hosting server??? please help me

  • Razan Fikri

    hello ravi i cannot open webSocket = new WebSocket(“ws://” + socket_url + “:” + port

    + “/WebMobileGroupChatServer/chat?name=” + name);

    i use alert(WebSocket);

    and alert is undefined;

    please help me.

  • divya

    sir, I tried to socket program in browser, it will not working properly, when I give the name and press the join button the page will be fade out and the next page will not coming.

    while if I remove

    (webSocket.onopen = function(event) { ) this line it will fade in the next page without any name in the listview. please help me sir.

    • see if you have syntax errors. That line has to be there. This is the function.

      webSocket.onopen = function(event) {
      $(‘#message_container’).fadeIn();
      if (event.data === undefined)
      return;
      };

      check whether the id of ‘message_container’ is same in the html file.

    • ajay

      In your main.js file this code should be some think lik,…

      webSocket = new WebSocket(“ws://” + socket_url + “:” + port

      + “/Your_project_name_url/chat?name=” + name);

      • akshay

        yes the line of code same…. but till now i have same problem

    • Yamini

      Hello Divya, Hope you fine…..Did you correct this error ?…..I have same prob….

  • Hi, Thanks for this great tutorial. I would like to implement cookies with this so that while opening new tabs on the same browser doesn’t create new sessions. Can you suggest any resources or ways in which i should proceed.

    I would also like to create database so as to store users and their passwords. Can you recommend some books or tutorials or tips which would help me.

  • İsmail Şahin

    Thank you very much nice tutorial

  • sourabh

    jquery-1.11.1.min showing
    errors in this file

  • Bulan Yurij

    Please help me!!!!!!! how to this in my hosting server???

  • sourabh

    how to remove error in jquery-1.11.1.min file.

  • vivek

    after entering name it fades but it remains blank after that…
    Please help me guys…
    Thanks in advance…

  • Chera Robinson

    Hi! I have a chat app, and I want to add the functionality to send files to my buddy, and my buddy also send me files too. How could I do this? Thanks! My buddy is in another city

  • How to run in host????

  • asc

    Hi Ravi your tutorial is really great. I would like to know how to choose the person with whom we want to speak with.

  • Khalil Serano

    Anyone fix Error! Connection is closed. Try connecting again. ?
    PLease

  • Muhammad Umair

    Everyone who are experiencing errors ensure the following steps!!

    1. Make sure that you use Tomcat 7.0

    2. Create all files ( index.html, jquery-1.11.1.min, style.css, main.js ) in WebContent folder, not in WEB-INF

    3-If you have created the project with different name make sure to change it in line 51 of main.js as shown in the following

    webSocket = new WebSocket(“ws://” + socket_url + “:” + port+ “/WebMobileGroupChatServer/chat?name=” + name);

    4- For people who are experiencing errors in “jquery-1.11.1.min”
    Go to this link: https://code.jquery.com/jquery-1.11.1.js
    Copy the code and replace it with your code in jquery-1.11.1.min

    I hope this helps!!!
    Thanks

    • Khalil Serano

      i solved it thank you :p
      now i have some problems in part2

      • Nikhil Kumar

        how did you manage to run at tomcat 7 ? is it not showing error as “The server does not support version 3.1 of the J2EE Web module specification.” ? i ran on tomcat 8 then and it’s giving “Error! Connection is closed. Try connecting again.” error . how you did it on tomcat 7 ?

    • Mohamed Ebrahim Hurab

      thank you 🙂

  • ivan

    Need help.. i can’t run project from tomcat 7.0 🙁 Tomcat cant start the project 🙁

  • Theasc

    I RAVI thanks for this turorial, there’s something i don’t understand and its how and when the sessionId is created. Also is it possible create a static sessionId that can be stored in the database and that could be reusable for the same client each time he connect himself ?

  • vivek

    page fades away when join button is clicked. please help.

    • Oussama GHOUAGH

      Hello ,
      I added the Java EE to the eclipse IDE that comes with my android SDK as described above however, it seems that there is a conflict, why ? I don’t have the answer for the moment. if you if you’ve tried what have been said below in the comments, and it still doesn’t work (fades) ,try with Eclipse for Java EE application.
      I suggest https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/keplerr
      Good luck

  • Yamini

    The page fades away when join button is clicked. please help me

  • akshay

    The page fades away when join button is clicked. please help me.
    if any one can help then please tell me..

  • The page fades away when join button is clicked. please help me.

  • asc

    I would like to know if it’s possible to maintain the webSocket connection after reloading the page ?

  • JACK

    Problem and fixed
    1: Page fades away, don’t forgot to add package and class in src floder.
    2: Access tomcat from another computer, Tomcat is case sensitive so url ../WebMobileGroupChatServer must same when access from other devices.

    hope this help you guy.

  • Thanks Ravi, I like your article which is very helpful for me. I build my own chat app. I have already built many chat application for android and other platforms. If you need any application regarding, kindly contact us.

    • ricky

      I need chat application for android … above application fade away after click

      • If you need chat application for android, share your contact or contact us on +1908-301-6001

        • Shahizzam

          hye RK Patel.can we talk in facebook. i need your help

        • sonu

          hi…i want to need source code of group chating with intruction
          send code or project file in below email id
          durgeshchandole19@gmail.com
          thank you….

        • Amar
    • Hotcaribbean Hotcaribbean

      Hi RK Patel. I have a question and i hope you can give me an answer please. How can i get this app running on a different server then localhost. I tried to change te ip adres to a other but that doesn’t work. Please help me

    • Vijay Chauhan

      hey rk patel ,this is my email vjcool.chauhan@gmail.com, please help me bro can you send one android chat aplication to me?

  • Josh

    Still can’t fix “Error! Connection is closed. Try connecting again.” while clicking on join button
    Has any body been able to fix this cause I couldn’t fix it and I have check through this discussion, no one with this bug has report it fixed

    • Gaurav

      did you solve this issue? I am facing the same issue

      • Ria

        Had the same issue – put out a javascript log and it says
        “Error during WebSocket handshake: Unexpected response code: 404”
        Tried with different browsers and also different servers (JBoss & Tomcat8). Googling the error didn’t help.
        Then I installed Tomcat7 and tried again: NOW IT’S WORKING!! 😀

        • Josmary

          I have the same problem , help

    • Leo Nam

      i have also meet the problem which is browser will pop up Error! Connection is closed. Try connecting again. when user login

      My solution is upgrade the Tomcat 7.0.34 to 7.0.68

      then it worked!!

  • Gubaz

    When I click Join Nothing is happening….
    can anyone help me about that ? :/

    • Josh

      Are you sure that you link the main.js script correctly? Make sure index.html, main.js, jquery-1.11.1.min.js and style.css are in WebContent

      • Gubaz

        Yes I’m Sure That They are at WebContent…
        When I Click Join page is reloading and thats all…
        I think I did everything according to tutorial…

  • Traviss

    What if I want to use android studio, can I add j2ee to it?

  • kashif

    The type java.lang.Throwable cannot be resolved. It is indirectly referenced from required .class files,

    this is shown when i import the package u gave me and it is not working plz tell me why it is happen..thanks

  • Muhammad Waleed

    good work bro

  • Mohit

    how to use websockets on a real website through a web host .
    Suppose – if I have a website http://www.abc.com (made through godaddy.com).
    how to start the sever file?
    can anyone help?
    thanks in advance..

  • Divya

    Heylo…The page fades away when join button is clicked…Please Can anyone help me …

  • swapnil

    [2015-03-14 11:40:03 – WebMobileGroupChatServer] D:eclipsenew bostonWebMobileGroupChatServerresvaluesstyles.xml:7: error: Error retrieving parent for item: No resource found that matches the given name ‘Theme.AppCompat.Light’.

    [2015-03-14 11:40:03 – WebMobileGroupChatServer]

    [2015-03-14 11:40:03 – WebMobileGroupChatServer] D:eclipsenew bostonWebMobileGroupChatServerresvalues-v11styles.xml:7: error: Error retrieving parent for item: No resource found that matches the given name ‘Theme.AppCompat.Light’.

    [2015-03-14 11:40:03 – WebMobileGroupChatServer]

    [2015-03-14 11:40:03 – WebMobileGroupChatServer] D:eclipsenew bostonWebMobileGroupChatServerresvalues-v14styles.xml:8: error: Error retrieving parent for item: No resource found that matches the given name ‘Theme.AppCompat.Light.DarkActionBar’.

    [2015-03-14 11:40:03 – WebMobileGroupChatServer]

  • Naser Tamaskani

    my local ip range is : 192.168.1.0/24 and i forward the local ip to my valid ip but the problem is on browser it has Eror Connection is Closed! but the Android App work well , what is the problem ?

  • Subhadip3

    I was initially getting ‘connection closed, try again’ error because I had changed port 8080 to 8082 while running tomcat but forgot to do the same in main.js.

  • Ajit

    Not able to download jquery-1.11.1.min.
    showing an error in the browser “The page isn’t redirecting properly”.
    how to solve it?

  • Arnab

    There is some error in the jquery-1.11.1.min. Please check once

  • Joseph

    I am facing this error: WebSocket connection to ‘ws://192.168.1.15:8080/WebMobileGroupChatServer/?name=ad’ failed: Error during WebSocket handshake: Unexpected response code: 200. Please help

    • Josmary

      disculpa solucionaste ese error? tengo el mismo

  • Joseph

    Its working now. Thanks for this tutorial

  • sanjay patel

    i want to add real web server how it done,and which ip address uses ?????

  • emmard

    can i substitute the java socket server with a nodejs websocket server? can it be done

  • Jose Stepherd Caster

    my script doesnt work, after pressing the join button nothing happens, and before i add someone i see that 23 people are online.. how come?

  • Evans

    Thank you Ravi mine works .I used to press the join button it just fade away.I had to delete the entire project. Create the project from the begin previously i was not select the target as apache 7 but was using apache 8, after correct the error and not pasting javaee-7.0 api.jar into lib because apache has its own websocket library it worked

  • Vijay Chauhan

    i got problem in pasting the jquery-1.11.1.min file ,it shows error in it , and the error is “missing semicolon”, please help me guys

    • sam

      I just right click on the link (don’t open) then choose “save link as” –> save–> you will get the file as is, then copy the file and put it under WebContent folder directly. … I have no errors in it. everything works fine.

  • aboud Engineering

    hi , i need help so the source code is valid and I do not errors but the problem is when I click on the botton “join” I was anything (she return a blank page without content ) please heeeeeelp 🙁

    • sam

      This solution, from the comments below works with me.

      MackAttack

      Yusuf

      20 hours ago

      I had the same error, i had index.html, main.js, style.css and the
      jquery min.js files in the wrong folder, make sure they are in the top
      level of the web content folder.

      • aboud Engineering

        all this files are in the right folder they are in the top
        level of the web content folder and she did not work 🙁 🙁 but when i copy style.css int the folder META_INF !! so other problem it come so both frames displays in the same window and she did not work :/

    • thanhhv

      Hey @aboudengineering:disqus ,

      You see about line 50 in main.js, and change “/WebMobileGroupChatServer/chat?name=” to “/your_proj/chat?name=”.

      sr my english :).

  • suraj

    cant do anything after clicking on join button….

  • Samir Bhatt

    Any one please help me for one to one chat ?

  • Satish Ujjammanavar

    above code working fine in my local machine(local server), exported same code(changed ip address) to .war file and uploaded to my shared server, but its not working, i am getting – java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
    Any one please help me , how to solve this problem ,

    • Mike

      Hello, did you solve this problem?

  • Miyuru Rajapaksha

    When running on the server i got the error message shown below , what should i do to solve this?

    HTTP Status 404 – /MobileGroupChatServer/

    type Status report

    message /MobileGroupChatServer/

    description The requested resource is not available.

    Apache Tomcat/7.0.59

    • move the html,css and js files to WEB-CONTENT folder

    • Ayana Aziz

      Is your problem solved?? plz reply i m also facing the same problem

  • Josmary

    hi guys,

    I have this error: WebSocket connection to ‘ws://192.168.1.103:8080/WebMobileGroupChatServer/chat?name=dd’ failed: Error during WebSocket handshake: Unexpected response code: 404

    I have tomcat 7.0.61 and java 8

    • Max-williams Kouacou

      Hi please have you found the solution?

  • Muhammet Ali Güneş

    Can you again upload or refresh like I can’t download or somebody do upload thank you

  • Baskar

    Thanks for sharing valuable information about

    Android Building Group Chat App using Sockets . http://www.bestqtptraining.com

  • Kamran

    click on join and just fade away …. nothing happened …. anyone have any idea how to fix it ?

    • chey rien

      same problem .i got it too .
      click button and no respons

      • Max-williams Kouacou

        hello!! which version of Tomcat you use?

        • Khoa Hansamu

          I also get the same issue and I using Tomcat with version “apache-tomcat-7.0.62”

    • Bheeshm Pareek

      Hi kamran You Got The Answer

      • Витор Томић

        I have the same issue, no errors in eclipse but nothing happens when i click the join button.

  • shishirumrao

    I’m getting 502 error on second part. Please fix that ….

  • programmer

    what if i download tomcat 8..?
    does it work…?

  • Taher

    No response on clicking join button.
    should we have to add form action

    • Bheeshm Pareek

      Hi Taher You Got The Answer………….

  • Koda

    Edit this line in Main.js for active the form after click button

    // Create a new instance of the websocket
    webSocket = new WebSocket(“ws://” + socket_url + “:” + port
    + “/Sample/chat?name=” + name);

  • Bheeshm Pareek

    Guys When I M Giving Any Name And Click Join,Name Is Disappearing And Nothing Is Happening,Please Anybody Help Me…….How I Will Solve This Problem…

  • Prashant Gosai

    say cast to session…

    // Mapping client name and session id
    nameSessionPair.put(session.getId(), name);

  • mohajara

    I changed the following line according my config

    webSocket = new WebSocket(“ws://” + socket_url + “:” + port
    + “/Sample/chat?name=” + name);

    but still after clicking Join the “connection error” apears

    and gives “404 get” error.
    It seems that the browser doesn’t find /chat page.
    What’s the problem, have any idea??

  • Saurabh Panchal

    Everything works fine but whenever a user leaves the conversation, the Browser says “Error! Connection lost.try reconnecting.” Although remaining users get a message that a user left.
    So many are getting this error but it is not fixed yet.Please help.this may not be error but there may be a good way to end the session…..@ravi8x:disqus

    • mohajara

      Hi Saurabh
      could you please help me with my and many other’s problem?

      Thank you

  • SivaMurugu Muthuramalingam

    Chat is working local machine with two different browser. converted into WAR file and upload on host server access the host URL from different locations, join window is visible , once type the name to join, it is get disappear the window. how to solve this problem, Urgent please.. mktg@tremendoussolutions.in

    • Prins Prem

      im getting same error please if you find let me know

  • SivaMurugu Muthuramalingam

    tel me any solution

  • Cheow Yi Long

    i’m having error on jquery-1.11.1.min missing semicolon. any idea?

    • Prins Prem

      if you are using eclipse and get that error just ignore it won’t effect your project

  • Khoa Hansamu

    Hi my friends,
    I have problem when run Web Group Chat below:

    “When I click join and nothing happens, the box just fades away”

    If you have fixed the issue before, please give me some hint to resolve it.

    Here’s video about problem : https://www.youtube.com/watch?v=zXwe2gfz2Ac&feature=youtu.be

    Thanks a lot

  • Prins Prem

    Hi im getting error in socket.java file. using eclips indigo for developing my project and I’m getting error in pacage info.androidhive.webmobilegrouchat

    Multiple markers at this line – The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files – The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

    Does anyone know why I’m getting error when I import Hashmap,util.map,common.collect.map in my java class

    • Hoang Nguyen

      Hello, I’m getting the same error. Have you found the solution? please, if you find let me know.

  • Mayank Khursija

    Hii, Can I add Selected Persons in this Group Chat, like there are total 10 persons but i want to add only 7 persons and How to do that. Thanks.

  • SyllabusBookCVR

    Works really awesome… thanks a lot Ravi 🙂

    • Jerrell Jones

      How did you get it to work? Every time I click join I get a blank screen. Which versions of everything did you use?

      • Alessio

        move index.html, jquery-1.11.1.min.js, main.js and style.css on the root of WebContent folder

      • SyllabusBookCVR

        Jerrell Jones, are u getting the blank screen on Web page or Android app???? I think there is an issue with loading the page, did u test the web app on local host tomcat server????

        • Jerrell Jones

          I get the error when running the web app on a localhost tomcar server. I have moved all the files to the correct location as well.

          • Me

            Did you find a solution? I am experiencing this issue as well.

        • Jerrell Jones

          I am getting the error while running the web app under a localhost implementation of tomcat. I have verified that all the files are in their correct locations.

  • Arshad

    Not working. Main screen fades off and nothing happens after chat. Cannot see the chat screen

  • Hi, I need to develop a chat app for a startup. Is following this post ok or should i look into Google’s Cloud Messaging Service and those stuff? I don;t have much idea, but i want to decide now on which way i should i proceed.

  • Alessio

    Hi, everything works great, tank you! But…if I would build an Ios app instead an Android app could it possible? Can I use the same server implementation? Thanks a lot in advance!

  • yogesh

    Hi ravi sir please make demo image and vidio sending using xmpp..like whatsup

  • ashish

    i’m getting an http-404….please help..

    • Axel Olaf

      Hey Ashis, have you already solved that? That happens to me too…

  • Naser Zahedi

    can edit this project for more chat groups ?

  • khushalmedani

    apparently, the android link does not work, can you please update the blog with correct link? i used

    http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-2/

    link

    • Naser Zahedi

      it is okay

      • khushalmedani

        Thanks! it is now working, might be just a hick-up I experienced:)

  • naveen

    my server code is not working when i give the name in textbox and pressbutton join then the screen feedin but the msg screen not coming

  • Bheeshm Pareek

    Ravi Tamada When I Am Clicking Join Button My text Disappear And Nothing Is Showing Dude Please Give Me Proper Solution or Send Me ur Code……….

    • Downgrade

      Same here… I’ve tried everything people have suggested bellow to solve that issue and nothing worked…

      • Bheeshm Pareek

        Hi AugustoRj I solved The Error Dude

        • Downgrade

          Me too! It was just the IP in the code. Just changed to my local IP and it worked… Same thing there?

          • Me

            Did you find a solution for this error? I am experiencing it as well, although the IP address matches my machine and jquery version matches it as well.

    • Roger

      Can you tell me how to solve this problem?
      please………

      • Bheeshm Pareek

        dude check which jquery u r using and same jquery version u should give in html.index file

  • Bheeshm Pareek

    Hi Ravi Thanku So Much Dude Love You Best Explanation And Best Tutorial But Dude Only 1 Issue When Clicking On Leavechatroom Its Showing connection is closed and dude i run this app on my android phone but when i am join every time with new name it showing 3 users already available how i removed them…..

    • Actually the use is removed when the socket connection is closed in public void onClose(Session session) method.

      You need to call client.disconnect(); in your android code on clicking the leave chat room button.

      • Bheeshm Pareek

        thanks DUDE

      • Real Slik

        Hey ravi, I followed everything exactly but i’m unable to get this to work. It asks for my name but once i hit enter it fades away. I set an alert before and after openSocket(); and it appears to not execute anything after openSocket(); I get a minor error in loading the descriptor which I’m not sure would have any impact but if you can help solve this issue it would be greatly appreciated as I see many people with the same problem here. btw all files (index.html, main.js, style.css and jquery-1.11.1.min.js) are all in the root of the web content folder.

        • In chrome use Developer Console to see if there were any javascript errors.

      • Real Slik

        I used to the developer console on chrome and this is what it said –

        WebSocket connection to ‘ws://localhost:8080/WebMobileGroupChatServer
        /chat?name=user1’ failed: Error during WebSocket handshake: Unexpected response
        code: 404(anonymous function) @ main.js:40

        i tried again and got


        WebSocket connection to ‘ws://localhost:8080/WebMobileGroupChatServer
        /chat?name=user1’ failed: Error in connection establishment: net:
        err::ERR_CONNECTION_TIMED_OUT @ main.js:59


        it seems to not be establishing a socket connection? am i doing something wrong I’m so confused? thx in advance

        • Is your local address ws://localhost:8080/ is correct ?

          • Real Slik

            yes i just changed it to localhost for the sake of posting it here in the forum. Just for the record the socket server that comes with tomcat as an example works but i really like how you did it. Is there anything i may be doing wrong? Or to anyone else who has solved this problem how did you do it? Thx everyone

          • Alexander Perez

            I’m having the same problem

  • Maksym Usyk

    Hi I have a problem with running an application so this how i loks like.
    and I could not download jquery-1.11.1.min, cause it openning in a new page as a script. So I copied it to the txt file and named it as jquery-1.11.1.min.js , could youy help me
    http://postimg.org/image/re5ipg1dh/

    thank you for attention

  • Priyanka Kadam

    i’m getting 404 error. plz solve

  • Lovekesh Khore Gurjar

    Please provide code of server site in php thanks for advance.

  • Me

    I have an error in jquery for this section of code “undefined”!=typeof window?window:this stating “The left hand side of this assignment must be a variable. When I click on Join in the chat window the name I entered disappears but otherwise the screen stays the same. Are these related? What correction should be done to the jquery code?

  • Michael

    Hello,

    When testing with web browser i get an error after i enter a name and press join, error is ‘The page at ‘my ip:8080’ says: Error! Connection is closed. try connection again.

    has anyone else had this and if so how to fix?

    Kind Regards

  • Razvan

    Have you skipped some steps? i cannot comprehend AT ALL how this is working. Is the SocketServer ever initialized? because it doesnt inherit anything.

  • Ayana Aziz

    hi ravi
    geting error 404 on running web app plz help

    HTTP Status 404 – /WebMobileGroupChatServer/

    type Status report

    message /WebMobileGroupChatServer/

    description The requested resource is not available.

    Apache Tomcat/7.0.64

    • Syarif Ibnu Miftahudin Al-Dami

      I have the same problem. Have you solved this yet?

    • Thato

      I have have the same problem Ravi Please Help.

      • Yeah solving this problem really difficult. You have to check the log in eclipse while starting the server. You can see the error there.

        • Pranusha Soma

          arey hi..i got d same error…404 resourse not available..could just help me out wid dis..pls!

    • Alexander Perez

      move index.html, jquery-1.11.1.min.js, main.js and style.css on the root of WebContent folder

  • Abhishek Tiwari

    Hi Ravi,

    Great web and android application. I was able to run both smoothly. It was just the thing that I wanted.

    In Web part I am unable to understand where the mapping of URL http://192.168.0.104:8080/WebMobileGroupChatServer/ is done to index.html page. How does the first page appear without this mapping.

    • Pranusha Soma

      hey hi dint u get any error like resource not found??
      if not pls share the solution

  • kushal power

    well its nice tut.. but when i enter name and click it will show – ERROR connection is cloed try connection again..? help me asap thanks

    • kushal power

      oh its working now i change this in main.js

      /**

      * Connecting to socket

      */

      function join() {

      // Checking person name

      if ($(‘#input_name’).val().trim().length <= 0) {

      alert('Enter your name');

      } else {

      name = $('#input_name').val().trim();

      openSocket();

      $('#prompt_name_container').fadeOut(1000, function() {

      // opening socket connection

      openSocket();

      });

      }

      return false;

      }

      • Real Slik

        what did you change? adding an extra openSocket(); before the $(‘#prompt_name_container’).fadeOut(1000, function() ?? I tried that and i’m still getting an error

    • Alexander Perez

      I’m having the same problem. Using the console from my browser i get this error:

      WebSocket connection to ‘ws://192.168.1.202:8080/WebMobileGroupChatServer/chat?name=asd’ failed: Error during WebSocket handshake: Unexpected response code: 404

      • abbas

        I can help you, please call me in telegram or whatsapp
        00989308561199

      • Lydia Burke

        Did you find an answer to this? Same thing for me

      • abbas

        hi
        Did you find an answer to this?
        plz tell me for this in whatsapp +989308561199 plz

  • masoud seraj

    fantastic example! thanks for sharing it!
    but i got a question!
    does the server creates threads and assigns to each client connecting to it automatically to support multi-client connection?

  • Pranusha Soma

    hie im facing an error-
    http status 404-/WebmobileGroupChatServer/
    please do help me!!!!

    • abbas

      hi
      I can help you, please call me in telegram or whatsapp
      00989308561199

    • Lydia Burke

      Did you get a solution?? I have the same problem. Very frustrating!

      • Raj Kr

        please put the index.html, jquery-1.11.1.min, main.js,style.cs in the webcontent not in web-inf….your issue reslove

    • ERRAJESH nasit

      its working if u need help contact me

  • aslahuddin

    i’ve test it and working perfectly…can we add another code to check who is currently available/online?

    • Anshul Tyagi

      How many days does it take to implement from starting?

      • aslahuddin

        It takes 1 to 2 days..but if you are an expert in programming, ot doesn’t take too long…

    • Ella

      hi aslahudin do you have the source code ? i have subscribe it but still can’t download it cause no email found.
      Can you send me the source code, this is my email nurlaela.bahamady@gmail.com
      thanx

  • Tanveer Bulsari

    Hey Ravi Sir,
    I used your same socket for my application, my concern is that I want to you a single socket for whole application in Android, so that I don’t need to initialize the socket variable now and than, can you help me solve my problem.

    • Muhammed Rajeef M K

      Have you tried extending from you Application Class and initializing your socket there and whenever you want to use it, get an instance of your socket from there ?

  • Nirav Jain

    I have successfully setup on my web host and its working fine from different browser and different wifi and data network. i am at the last step where i am building this app in android studio and MainActivity is showing error WebSocket library is deprecated and replaced by AndroidAsync..
    Can anyone modify the Whole code of MainActivity.class and upload it…

    • Firmansyah Rizqy

      Hay Nirav, can you help me? , i have tried to upload it on my web host but when i clicked join button it always show me an error “failed: Error during WebSocket handshake: Unexpected response code: 404” , i got this error message when i tried to run it on my web host, when i run on my local this application work perfectly.. can you help me to find out why its hapend..

      Thank you.

      • Nirav Jain

        No use. because you cant create a android app since websocket has been deprecated and replaced by async. i have asked several times to author ravi tamada but he is not replying on website or facebook nor on twitter. if you somehow succeed in making android app than reply me i will surely help yo

        • Firmansyah Rizqy

          Hay Nirav, thanks for your reply.
          I’m so sorry before, I mean I tried to run it web to web (without android apps). Just like in your link , I have tried to join in your group chat and its work fine. But, when I try to run my apps on my web host I got that error message (404) when I click “join” button… Can you give me some advice to deploy it on my web host?
          Thanks.

          • Velmurugan Mariyappan

            could you tel me how can you create URL? how can i create database? Explain me Please.

            I am asking about “create DB” in Local.

          • Firmansyah Rizqy

            I’m so sorry, I don’t know what you mean..

            Create URL : you should be have your own web hosting and domain

            Creaet DB in Local : you should be have a database apps in your local machine like mysql or you can use xampp (web server that include mysql)

            Is that answer what you looking for?

          • Nirav Jain

            You just need to change the websocet URL address in the main.js file with port

            Example :- mytomcatapp-example. Rhcloud.com:8000

          • Firmansyah Rizqy

            I have tried to use an IP address, and use my domain name in the main.js file

            Exmpl :

            1. I used : 111.222.3.11:8080
            2. I used : mydomain.com:8080

            Both of them are still show me that error message.

    • Ayush Nigam

      @nirav_jain:disqus ,
      Sir can you please help. I am done with inputting the name but messaging screen not coming….

      • Shubham Talbar

        Did you find any solution to this?

    • Adedara Klever Olanrewaju

      Hey Nirav,
      How are you doing? I will like you to give me a brief discussion on how u were able to setup on web host where it can work from different browser and different wifi and data network.
      Please this is urgent..
      Thanks

  • Nirav Jain

    anyone help please

  • Bassu Rai

    when i run it in my chrome browser its show this webpage not available

  • Jean Francois Tate

    Hi to everyone. the webapp starts, but when i try to join the chat, i get the error: “Error! Connection is closed. Try connecting again.”. Browser is websocket enable and i paste my ip in main.js. Any ideas??? Thanks

    Answer: For those with the same problem, just delete the javaee-api-7.0 then tomcat in my case v8 has his own websocket´s lib.

  • Bassu Rai

    how can i download source code,when i subscribe with my email id its show ”An email has been sent to your email address. Please verify your account” but there is nothing in my inbox, how can i download it ?

    • radek

      Same problem. Did you solve it?

  • Lew Wei Hao

    Hi how do I get this to work if I want to host this webapp over a real online server such as 000webhost? What ip address do I put in my main.js? I tried my public ip and did port forwarding to my local ip on port 8080 but it doesn’t work.

    Thanks

    • Stephen Kelly

      Any joy 000webhost?

  • Nishant Meena

    hi sir i have error on brpwser 404

    The requested resource (/WebMobileGroupChatServer/) is not available.

    • Ayush Nigam

      Keep the html file under WebContent folder itself ,not WEB-INF .

      • Vipin Maurya

        it help me!!
        Appreciated your suggestion!!!

  • Shahzod

    Hi, I have problem, can you help me. I can’t run this project. My mail is shahzod.khusinov@gmail.com.

  • Jigar Moradiya

    Hello please help me
    When i give the name in textbox and join then the screen feedin but the message screen not coming

    • Raj Kr

      i m getting the same problm if u got solution please tell me

    • Raj Kr

      i resolve the issue

      • Vishnu

        Could you please share the solution here ?

  • Ayush Nigam

    @jigarmoradiya:disqus Mine also is same problem.
    I am using Weblogic Server 12.1.3 and changed port to 7001 with localhost
    But after inputting the name the message window isnt opening .. Please mail me : ayushnigamsworld@gmail.com

    • Shubham Talbar

      Did you get any solution for this?

  • lakshmanan

    Do you have the same code or tutorial using android studio?

    • Rana Saqib Manj

      Have you done this project in android studio ???

      • ERRAJESH nasit

        Hey You must click from welcome screen =>import project( Eclipse->ADT)

        • Mario German

          I have a project in Android Studio and I want to include in my project a chat, as it could be done, thank you.

  • Raj Kr

    I tried the code working fine.. but i m facing the problem…”webchatserver” running ok but after adding the name and click on join the page going white only “Android WebSockets Chat Application” is showing …please tell me the problem….

    one more problem in the application on android after enter the name and join then chat apper and toast message HTTPResponeException. but my device is ping with my system…so please get e some solution…

    • Shubham Talbar

      Did you find any solution?

    • Akhil

      Did you find any solution? If YES Please let me know, EMAIL ID : akhilgite@gmail.com

    • Miroslav Procházka

      do u have solution for that? email it to me pls : proocho@gmail.com

  • Raj Kr

    please go through the screenshot url please specify me the solution i had tried every possible ways

    http://i64.tinypic.com/2liy2pz.png

  • Raj Nasit

    can we broadcast message to all without For loop of sessions?

  • Anne Lingesh

    Can we do it in android studio?

    • ERRAJESH nasit

      ha beta

      You must click from welcome screen =>import project( Eclipse->ADT)

  • Ashok Kumar Shaw

    I am going to develop a chat app in android.in which I want to include the feature like create group,group chat, personalchat which one would be better …developing through socket programming or gcm..

  • cr7abraham

    i have a problem

    —–ADVERTENCIA: Failed to scan JAR [file:/C:/Users/MADRIGAL/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/proyectochat/WEB-INF/lib/javaee-api-7.0.jar] from WEB-INF/lib

    java.util.zip.ZipException: error in opening zip file

    at java.util.zip.ZipFile.open(Native Method)

    at java.util.zip.ZipFile.(ZipFile.java:215)

    at java.util.zip.ZipFile.(ZipFile.java:145)

    at java.util.jar.JarFile.(JarFile.java:154)

    at java.util.jar.JarFile.(JarFile.java:91)

    at sun.net.www.protocol.jar.URLJarFile.(URLJarFile.java:93)

    at sun.net.www.protocol.jar.URLJarFile.getJarFile(URLJarFile.java:69)

    at sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:109)

    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:122)

    at sun.net.www.protocol.jar.JarURLConnection.getJarFile(JarURLConnection.java:89)

    at org.apache.tomcat.util.scan.FileUrlJar.(FileUrlJar.java:41)

    at org.apache.tomcat.util.scan.JarFactory.newInstance(JarFactory.java:34)

    at org.apache.catalina.startup.ContextConfig$FragmentJarScannerCallback.scan(ContextConfig.java:2679)

    at org.apache.tomcat.util.scan.StandardJarScanner.process(StandardJarScanner.java:259)

    at org.apache.tomcat.util.scan.StandardJarScanner.scan(StandardJarScanner.java:178)

    at org.apache.catalina.startup.ContextConfig.processJarsForWebFragments(ContextConfig.java:1915)

    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)

    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:887)

    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:387)

    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)

    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)

    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5472)

    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)

    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:4088)

    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)

    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1342)

    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1543)

    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1553)

    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1553)

    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1521)

    at java.lang.Thread.run(Thread.java:745)

  • Thulisile Thwala

    Hi i have a problem,when i press the join button it shows nothing just plain white page please kindly help via solution my email is 2leethwala@gmail.com

    • Sergio Varher

      If you have apache installed, stop the service or uninstall it

      • Thulisile Thwala

        i stopped apache on xampp control panel but it’s still doing the same thing.I’m not sure about uninstalling it perhaps it might interfere with the other applications i’m doing currently

        • ishav

          I tired somewhat similar code on glassfish server it was working fine.

  • iman kazemayni

    how can i run server socket section on a linux server. i buyed a linux host and domain so can i run server socket part with java language on this server ? how ? just copy and paste ?

  • sohil jain

    can we integrate this code with android studio?

    • ERRAJESH nasit

      yes beta

      • sohil jain

        btu when i import this code in android studio then it doesn’t import package for gcm. i tried all possible solution for add gcm library i cant understand why it it not import?

        • ERRAJESH nasit

          You must click from welcome screen =>import project( Eclipse->ADT)

          • Mario German

            Me too, I have a project in Android Studio and I want to include in my project a chat, as it could be done, thank you.

          • Iman marashi

            WebContent is an Eclipse project, but not an Android Eclipse project.

            Please select the directory of an Android Eclipse project(which for example will contain
            an AndroidManifest.xml file) and try again.

          • Mario German

            Thanks for your reply, but I still do not understand how I should do the process correctly, I can not find the files that indicate much less how to develop it, I appreciate your collaboration.

  • Priya Jain

    Error! Connection is closed. Try connecting again. is the error and my var socket_url = ‘192.168.1.3’;
    var port = ‘8084’;. I am running server part in NetBeans . What is exact problem.

  • public function getAllChatRooms() {

    $stmt = $this->conn->prepare(“SELECT chat_room_id,name FROM chat_rooms”);

    $stmt->execute();

    $tasks = $stmt->get_result();

    $stmt->close();

    return $tasks;

    }

    In my rent server, get_result doesn’t work, please help me to fix it.

  • Sobuj Moniruzzaman

    Hey Ravi Sir,
    It works fine for me. Thank you.

    • cheryy Suyatmi

      Help Me..? I have problem this.

      HTTP Status 404 – /WebMobileGroupChatServer/

      type Status report

      message /WebMobileGroupChatServer/

      description The requested resource is not available.

      Apache Tomcat/7.0.69

  • cheryy Suyatmi

    haii.. I have problem. what the solution this? please help me..

    HTTP Status 404 – /WebMobileGroupChatServer/

    type Status report

    message /WebMobileGroupChatServer/

    description The requested resource is not available.

    Apache Tomcat/7.0.69

    • ragnaroksg

      Same problem….

      • cheryy Suyatmi

        what solution for this, anyone know?

  • arj

    It is working. You have to put the files (index, jquerry, main, style) directly in WebContent folder and not in its subfolder (WEB-INF). And “jquery-1.11.1.min.js” might give error (left hand side must be a variable) in one line, just ignore that. You can still run the project.

    • salah

      where is one line i dont find it

      • arj

        Its OK if you dont see it. I said to ignore it anyway.

    • an dres

      thank you very much, it was perfect

  • salah

    not working why i need it

  • Iman marashi

    I can not download code! why?

    • Please try now. My server disk is full, that’s why all the services are crashed 🙁

  • Lambros Hitiris

    This is the most complicated example ever created!

    • Nothing is complicated, you are just getting started!

  • an dres

    great job, thank you a lot

  • rifqi

    by now, do u still prefer using scoket for realtime chat? how about using xmpp?

  • Adedara Klever Olanrewaju

    Hey Mr Ravi, its me again..
    I was wondering if this could be hosted on an online url using a general IP address where anyone from anywhere can just open the url and just begin to chat ASAP..
    This is urgent

  • Mario German

    Hello Ravi, I have a project in Android Studio and I want to include in my project a chat, as it could be done, thank you.

    • Iman marashi

      Are you do it in Android Studio? i can not implement server side on my VPS 🙁

      • Mario German

        Yes, my project is developed in Android Studio and I do not know how to develop it, I appreciate all the help that I can provide.

  • akash

    hello sir,
    in my project i have http 404 error. plese heelp me..

  • akash

    HTTP Status 404 – /WebMobileGroupChatServer/

    type Status report

    message /WebMobileGroupChatServer/

    description The requested resource is not available.

    Apache Tomcat/7.0.69

    that is error

    • The url you are accessing is incorrect or project is not configured correctly. Search for ‘apache java project url 404 error’

  • Thiago Oliveira

    Hi Ravi, this is a great tutorial thanks. So, I would like to know if there is any way to have a quantity user for room?! Thank you so much. Best regards, Thiago Oliveira.

  • Abhishek

    Hello Ravi,
    Thanks for the super explanative code. When I am running the same source code, I am able to get the first page on http://localhost:8080/WebMobileGroupChatServer/ but when I enter same name instead of showing chat room it shows white page. Can you please help me with it.

    Cheers,
    Abhishek

  • Abdullah Al Hasan

    Please update the post for Android Studio. 🙂

  • Shathish R

    Hi Ravi,
    Thanks for sharing this websocket application. Really well explained.

  • Ajinkya Badve

    After successfully runing the server and entering in char room their is white screen occures and the error is shown at this link https://goo.gl/photos/C4TTM3GdUDx7m6hKA .Can you please help me

  • Scarface F.

    Hey how can I run the server for it

  • Flo Reich

    how to run the socket server with linux ?

  • ashish

    its great tutorials ravi sir…thanks
    But how can i host on godaddy server and if i want to host in my server then which procedure i should follow because i dont want to localhost i directly chat from server so can you just lights me to upload project on server?

    • Hi

      This article helps you in hosting the services on digitalocean. Similar procedure applies to godaddy except you get all the services installed already.
      http://www.androidhive.info/2015/03/android-hosting-php-mysql-restful-services-to-digitalocean/

      • ashish

        thanks ravi sir…i m trying now.

      • ashish

        hello ravi sir, i was try but didn’t success to host…i am not getting
        that how can i host my /AppChatServer/ which is my /Dynamic Web Project/.

      • Bhuwan Ghosh

        Hey Ravi… Very helpful guide… isnt there any alternative to that JQuery code… something more simple and easy to understand using javascript…

        • Hi Bhuwan,

          jQuery is much simpler than plain javascript.

          • pammy

            i agree. jQuery is far simpler

  • jai

    Hello sir ,
    why i cant download your code?

  • viky

    hello ravi, how many devices we can connect?? is there any limit ??

  • Sống Khỏe

    Hi Ravi, when I click JOIN button, it don’t display chat room. Why?

    • Virat Gajjar J

      hey song,i am facing the same problem, did you find the solution for it? then please share

  • kari

    error main.js

    $(document).ready(function() {
    ^

    ReferenceError: $ is not defined

    • pammy

      did you include jquery in your project. or u can replace $ with jQuery instead

  • Dimpy Ladva Jobanputra

    Hi, What is the best way to develop social chat app like whatsapp means multiple group and one one to one chat ?? XMPP or Socket or FCM ?? can you tell me please.

  • milan

    when i am trying to send message to server it receive encrypted message. i don’t understand why is this happening?

  • Matheus Dutra Bloebaum

    Any idea how to put this in EC2 instance?

    • Matheus Dutra Bloebaum

      nvm, I just connected using my public IP in EC2 and it worked lol, thx anyway

  • ERYOYO

    Hi All,

    I am new to this socket programming. I also want to develop the chat application using socket programming but on ANDROID STUDIO. Any help is really appreciated.

    thanks,

  • Ahana

    hi….can you tell me one things does this work on android studio …i am beginner so tell me why u use css here and html…please answer

  • Gemson Gonzales

    Hello again Ravi, I just want to know if it’s possible to send json objects from web app to my android app that I created with Android Studio i’m currently using nv-websocket-client for my android app and planning to use node.js for my server

    • Yes, you can use sockets to send data from server to app.

  • Excellentwebworld Developer

    Hello,
    I am android developer. And i am developing an android app which is like chatting app. And I am using socket for chatting. So my question is how to send image and file on sever using socket in android and how to receive that image and file on server using Node.js ?
    Please help me.
    Thanks.

  • inaisse

    Hello,
    the file jquery-1.11.1.min is giving errors !!!
    what i do please!!

  • William K.

    How do you send message to a specific client?

  • RAGASHREE N

    How to get confirmation that client received the message from server??

  • Daksh Gargas

    Hi, as in 2017, we use Android Studio and Tomcat is not available in AS and it requires IntelliJ Idea UltimateEdition in order to run. So what should I do. Which alternative should I go for?

  • Kapil Mehta

    Hi,
    How to deploy this Chat server on aws Beanstalk or Aws tomcat, I’m getting 500 http error on aws.

  • Vaibhav Joshi

    HI,
    can we make an offline chat app? If so then can you provide a tutorial about that. I am new to android .pls help

    • How can you send messages to other party if there is no internet connection?