Reputation: 11
I have multithreaded chatting java server which can handle number of clients (java). They can simultaneous talk with each other. They are connected through network socket. Besides their own conversation words, my purpose is to display the conversation words they do in web browser through web application. I am thinking about JavaScript but couldn't figure out how to implement javascript for web application because I will need object or data to pass to javascript side from server( java) side.
Following is the multithreaded server and this works fine with multiple clients.
public class GoodChatServer {
………
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
….
}
} finally {
…..
}
}
private static class Handler extends Thread {
……….
this.socket = socket;
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
out.println("SUBMITNAME");
name = in.readLine();
if (name == null) {
..
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
Upvotes: 1
Views: 2287
Reputation: 1545
There are a plethora of ways to display chat information from a Java server in a browser using JavaScript. Since you are already using sockets for your Java clients, one option would be to use WebSockets. Oracle provides an introduction to Java Websockets here, which should help you with the server side of things. Mozilla also has a tutorial for writing browser-based websockets here.
Another option you may consider is to relay your data across global real-time network, such as PubNub. PubNub provides a Java API and JavaScript API which will allow you to publish messages from your Java server to your JavaScript clients, using code such as:
<script src="http://cdn.pubnub.com/pubnub.min.js"></script>
<script>(function(){
var pubnub = PUBNUB.init({
publish_key : 'demo',
subscribe_key : 'demo'
})
pubnub.subscribe({
channel : "my_chat_channel",
message : function(m){ alert(m) }, //Display the chat message
})});</script>
On the Java server, you'd write your publish code:
Pubnub pubnub = new Pubnub("demo", "demo");
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
System.out.println(response.toString());
}
public void errorCallback(String channel, PubnubError error) {
System.out.println(error.toString());
}
};
pubnub.publish("my_chat_channel", "Here is my amazing chat message!" , callback);
PubNub is currently free for up to 1 million messages per month. Good luck!
Upvotes: 1