i just completed a web based chat application based on ajax/php. But the problem with this app is that it has to continuously poll server to check for new messages, which in turn overloads the server if many people are using this app simultaneously.
now i want to implement a socket based chat app in JavaScript. I know there is no support for sockets in JavaScript so i decided to use "Flash as a socket gateway for JavaScript" i am using Linux and and new to flash. can someone help me with how to achieve this.
basically,
1) I want to make a small SWF object that just handles socket logic(minimum width and height so i can hide it easily with -ve margin.
2) I want to access this swf object with JavaScript
i got a code for simple socket in actionscript (from internet) but i cannot get it to compile using mxmlc(free flash compiler).
heres the code...
myXML = new XMLSocket;
myXML.onConnect = handleConnect;
myXML.onXML = handleXML;
myXML.onClose = handleDisconnect;
myXML.connect("http://www.yourServer.com", 12345);
function handleConnect(connectionStatus){
connectionStatus ? trace("Connected.") : trace("Connection failed.");
}
function handleXML(xmlObject){
trace("Object recieved:: "+xmlObject);
}
function sendXML(textToSend){
myXML.send(new XML('"+textToSend+""));
}
function handleDisconnect(){
trace("Connection lost.");
}
function closeConnection(){
trace("Closing connection to server.");
myXML.close();
}
i got a better code but this also does not compile
package
{
import flash.errors.*;
import flash.events.*;
import flash.net.Socket;
public class ChatSocket extends Socket
{
public var host:String;
public var port:uint;
private var socket:Socket;
public static var SOCK_CONNECTED:String = "onSockConnect";
public static var SOCK_IOERROR:String = "onSockIOError";
function ChatSocket(h:String, p:uint)
{
host = h;
port = p;
socket = this;
super(host, port);
initListeners();
}
public function sendMessage(str:String):void
{
if(connected)
{
socket.writeUTFBytes(str + "\n");
}
else
{
trace("Not connected, message not sent!");
}
}
public function readMessage():void
{
if(connected)
{
var str:String = socket.readUTFBytes(socket.bytesAvailable);
trace("Socket Server Response: " + str);
}
else
{
trace("No message read, not connected!");
}
}
private function initListeners():void
{
socket.addEventListener(Event.CLOSE, closeHandler);
socket.addEventListener(Event.CONNECT, connectHandler);
socket.addEventListener(IOErrorEvent.IO_ERROR,
ioErrorHandler);
}
private function closeHandler(event:Event):void
{
trace("Connection to [" + host + "] closed");
}
private function ioErrorHandler(event:IOErrorEvent):void
{
dispatchEvent(new Event(SOCK_IOERROR));
}
private function connectHandler(event:Event):void
{
trace("Connected to [" + host + "]");
dispatchEvent(new Event(SOCK_CONNECTED));
}
private function socketDataHandler(event:ProgressEvent):void
{
readMessage();
}
}
}
var sock:ChatSocket;
sock = new ChatSocket('127.0.0.1', 9990);
sock.addEventListener(ChatSocket.SOCK_CONNECTED, connected);
sock.addEventListener(ChatSocket.SOCK_IOERROR, ioError);
function ioError(e:Event):void
{
trace("Cant connect to " + sock.host + " on port " + sock.port);
}
function connected(e:Event):void
{
sock.sendMessage("are you hungry?");
}
ERROR IS:
localhost bin]$ ./mxmlc ChatSocket.as
Loading configuration file /home/lk/Documents/flex_sdk_3.4/frameworks/flex-config.xml
/home/lk/Documents/flex_sdk_3.4/bin/ChatSocket.as: Error: A file found in a source-path can not have more than one externally visible definition. ChatSocket;sock;ioError;connected
You may wish to check out gimite's web-socket-js. This is a socket gateway that conforms to the work-in-progress Web Socket API, so in future as browsers implement native WebSocket it will automatically switch over to the Flash-free alternative.
The following code lies outside the class and package {} blocks. That is not allowed.
var sock:ChatSocket;
sock = new ChatSocket('127.0.0.1', 9990);
sock.addEventListener(ChatSocket.SOCK_CONNECTED, connected);
sock.addEventListener(ChatSocket.SOCK_IOERROR, ioError);
function ioError(e:Event):void
{
trace("Cant connect to " + sock.host + " on port " + sock.port);
}
function connected(e:Event):void
{
sock.sendMessage("are you hungry?");
}
Declare a document class (that extends Sprite) and move ioError and connected methods to it. Make sock an instance variable instead of a local variable and add the declaration part of sock into its constructor.
//DocClass.as
package
{
public class DocClass
{
private var sock:ChatSocket;
public function DocClass()
{
sock = new ChatSocket('127.0.0.1', 9990);
sock.addEventListener(ChatSocket.SOCK_CONNECTED, connected);
sock.addEventListener(ChatSocket.SOCK_IOERROR, ioError);
}
private function ioError(e:Event):void
{
trace("Cant connect to " + sock.host + " on port " + sock.port);
}
private function connected(e:Event):void
{
sock.sendMessage("are you hungry?");
}
}
}
Related
I can't figure out when and where exactly the "greetings" room is created in the code.
This is my js code
function connect() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {//here it subsribe to this chat channel
showGreeting(JSON.parse(greeting.body).content);
});
});
}
and this is java
#Controller
public class GreetingController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
In js I see that message will be send to "/topic/greetings", and in java code I see where will be server send answer(/topic/greetings), but where in code this topic have been created ?
I'm working on setting up my first websocket server for a communications app. I can't seem to figure out how websockets are implemented in Java.
I've tried, unsuccessfully, creating an annotation based Endpoint, but I'm not sure where the client info is going to come through. This is basically the gist of my code, without going into mundane details.
I'm trying to make the class MessageHelper deal with the websocket info transfer, I just can't grasp how to actually get the transfer there.
class MainServer implements Runnable {
// VARIABLES
ServerSocket serverSocket = null;
int port;
// CONSTRUCTORS
MainServer(int p) {
this.port = p;
}
// METHODS
public void run() {
openServerSocket();
while(!isStopped()){
try{
clientSocket = serverSocket.accept();
} catch(IOException e) {
// Do something
}
new Thread(new MainThread(clientSocket)).start();
}
}
}
// Other methods below.
public class MainThread {
final Socket socket;
MainThread(Socket s) {
this.socket = s;
}
public void run() {
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String input = br.readLine(), read = br.readLine();
while(!input.isEmpty()) {
read += "\n";
read += input;
input = br.readLine();
}
/**
* Everything works fine, I'm just not sure where to go
* from here. I tried creating MessageHelper into the java
* websocket implementation using annotations but it did not
* accept input from the client after the handshake was
* made. My client would send something but it would just
* give and EOFException.
**/
if(websocketHandshakeRequest(read)) {
MessageHelper messageHelper =
new MessageHelper(this.socket);
} else {
// Do something
}
} catch(Exception e) {
// Do something.
}
}
}
Don't be confused about the name WebSocket. A TCP socket and a WebSocket are entirely different kind of "sockets".
In Java you use a ServerSocket for TCP sockets. TCP is a transport layer protocol used to implement application layer protocols like POP3 and HTTP.
WebSocket is a HTTP/1.1 protocol upgrade commonly used in web servers and web browsers. You cannot use a ServerSocket for the WebSocket protocol, at least not so straight forward as you might think. First, you have to implement the HTTP/1.1 protocol and then the WebSocket protocol on top of that.
In the Java world you can use web servers like Tomcat or Jetty which provide WebSocket implementations and a high level Java API. This API is part of the Jave Enterprise Edition (JEE). See also the Jave EE 7 Tutorial - Chapter 18 Java API for WebSocket.
E.g. Jetty is a lightweight JEE web server which can be embedded in your application or run as a stand-alone server. See Jetty Development Guide - Chapter 26. WebSocket Introduction.
So in a Java web application running in a WebSocket enabled JEE web server like Jetty you can implement a server side WebSocket as follows:
package com.example.websocket;
import org.apache.log4j.Logger;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
#ServerEndpoint("/toUpper")
public class ToUpperWebsocket {
private static final Logger LOGGER = Logger.getLogger(ToUpperWebsocket.class);
#OnOpen
public void onOpen(Session session) {
LOGGER.debug(String.format("WebSocket opened: %s", session.getId()));
}
#OnMessage
public void onMessage(String txt, Session session) throws IOException {
LOGGER.debug(String.format("Message received: %s", txt));
session.getBasicRemote().sendText(txt.toUpperCase());
}
#OnClose
public void onClose(CloseReason reason, Session session) {
LOGGER.debug(String.format("Closing a WebSocket (%s) due to %s", session.getId(), reason.getReasonPhrase()));
}
#OnError
public void onError(Session session, Throwable t) {
LOGGER.error(String.format("Error in WebSocket session %s%n", session == null ? "null" : session.getId()), t);
}
}
You register your class as a WebSocket handler for the specific path with the #ServerEndpoint annotation. Your WebSocket URL is then ws://host:port/context/toUpper or wss://host:port/context/toUpper for HTTPS connections.
Edit:
Here is a very simplistic HTML page to demonstrate the client side connection to the above WebSocket. This page is served by the same webserver as the WebSocket. The webapplication containing the WebSocket is deployed at context "websocket" on localhost port 7777.
<html>
<body>
<h2>WebSocket Test</h2>
<div>
<input type="text" id="input" />
</div>
<div>
<input type="button" id="connectBtn" value="CONNECT" onclick="connect()" />
<input type="button" id="sendBtn" value="SEND" onclick="send()" disable="true" />
</div>
<div id="output">
<h2>Output</h2>
</div>
</body>
<script type="text/javascript">
var webSocket;
var output = document.getElementById("output");
var connectBtn = document.getElementById("connectBtn");
var sendBtn = document.getElementById("sendBtn");
var wsUrl = (location.protocol == "https:" ? "wss://" : "ws://") + location.hostname + (location.port ? ':'+location.port: '') + "/websocket/toUpper";
function connect() {
// open the connection if one does not exist
if (webSocket !== undefined
&& webSocket.readyState !== WebSocket.CLOSED) {
return;
}
updateOutput("Trying to establish a WebSocket connection to <code>" + wsUrl + "</code>");
// Create a websocket
webSocket = new WebSocket(wsUrl);
webSocket.onopen = function(event) {
updateOutput("Connected!");
connectBtn.disabled = true;
sendBtn.disabled = false;
};
webSocket.onmessage = function(event) {
updateOutput(event.data);
};
webSocket.onclose = function(event) {
updateOutput("Connection Closed");
connectBtn.disabled = false;
sendBtn.disabled = true;
};
}
function send() {
var text = document.getElementById("input").value;
webSocket.send(text);
}
function closeSocket() {
webSocket.close();
}
function updateOutput(text) {
output.innerHTML += "<br/>" + text;
}
</script>
</html>
If you're willing to use Java Spring - which I think would be great for your use case, it's pretty easy to setup a websocket server and client connection.
There's an example here - https://spring.io/guides/gs/messaging-stomp-websocket/
I'm following this tutorial : https://www.baeldung.com/websockets-spring
I tested the app and it works perfectly when running on the embedded-tomcat server. However, when I try to deploy and run the same app on an external tomcat server it breaks, because instead of the URL being
localhost:8080/chat
it becomes
myhostIP:port/spring-boot-web-jsp/chat
So I modified the javascript file adding /spring-boot-web-jsp in front of the existing URLs. When I run the webapp the sockets connect successfully and send data. However now my Spring MVC Controller doesn't work.
My javascript :
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility
= connected ? 'visible' : 'hidden';
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS('/spring-boot-web-jsp-1.0/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/spring-boot-web-jsp-1.0/topic/messages', function(messageOutput) {
showMessageOutput(JSON.parse(messageOutput.body));
});
});
}
function disconnect() {
if(stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendMessage() {
var from = document.getElementById('from').value;
var text = document.getElementById('text').value;
stompClient.send("/spring-boot-web-jsp-1.0/app/chat", {},
JSON.stringify({'from':from, 'text':text}));
}
function showMessageOutput(messageOutput) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(messageOutput.from + ": "
+ messageOutput.text + " (" + messageOutput.time + ")"));
response.appendChild(p);
}
My Controller :
#MessageMapping("/chat")
#SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
String time = new SimpleDateFormat("HH:mm").format(new Date());
return new OutputMessage(message.getFrom(), message.getText(), time);
}
My message broker :
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat");
registry.addEndpoint("/chat").withSockJS();
}
}
I've tried modifying the Controller to :
#MessageMapping("app/chat")
#SendTo("/topic/messages")
public OutputMessage send(Message message) throws Exception {
String time = new SimpleDateFormat("HH:mm").format(new Date());
return new OutputMessage(message.getFrom(), message.getText(), time);
}
#MessageMapping("spring-boot-web-jsp-1.0/app/chat")
#SendTo("spring-boot-web-jsp-1.0/topic/messages")
public OutputMessage send(Message message) throws Exception {
String time = new SimpleDateFormat("HH:mm").format(new Date());
return new OutputMessage(message.getFrom(), message.getText(), time);
}
and a bunch of other variations but none of them work.
How can I modify the Controller and javascript file to work when testing through external Apache Tomcat as well as embedded (setting a relative URL of some sort)? And how can I get this to work properly on the external Tomcat?
Remove your tomcat/webapps/ROOT directory
Rename your final jar/war/ear file to ROOT.jar/war/ear
Deploy it on tomcat
Tomcat will deploy your app under root directory localhost:8080/chat
My scenario is this:
Server application A saves a assigned task to a database.The change in
database is monitored by a change notification and there is a server hub running.
Client side Javascript code,running along with server application B, has to connect to the remote hub. so that it receives a notification whenever App A inserts into the DB.
Here is my server code
I had downloaded owin.cors package.
[assembly: OwinStartup(typeof(Global))]
namespace Demo
{
public class Global : System.Web.HttpApplication
{
public static void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors=true,
};
map.RunSignalR(hubConfiguration);
});
}
notificationHub.cs
public class NotificationHub : Hub
{
public static Hashtable UserIdLookupTable = new Hashtable(20);
public static Dictionary<string,Job> PendingNotificationTable = new
Dictionary<string,Job>(20);
public void OnChange(string userId,string task,string description,string
duration)
{
if (UserIdLookupTable.ContainsKey(userId))
{
this.Clients.Client(UserIdLookupTable[userId].ToString()).Notify(userId,
task);
UserIdLookupTable.Remove(userId);
if (PendingNotificationTable.ContainsKey(userId))
PendingNotificationTable.Remove(userId);
}
else
PendingNotificationTable.Add(userId, new Job(userId, task,
description, duration));
}
public override Task OnConnected()
{
string name =Context.QueryString["userId"];
registerConnectionId(name);
return base.OnConnected();
}
public void registerConnectionId(string userId)
{
if (UserIdLookupTable.ContainsKey(userId))
UserIdLookupTable[userId] = Context.ConnectionId;
else
UserIdLookupTable.Add(userId, Context.ConnectionId);
if(PendingNotificationTable.ContainsKey(userId))
{
Job j=PendingNotificationTable[userId];
OnChange(j.UserId, j.Description, j.EmployeeName, j.Duration);
}
}
Client Side Code connecting to the remote hub
My script includes
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="~/Scripts/HubConnection.js"></script>
HubConnection.js
function ConnectToHub()
{
jQuery.support.cors = true;
$.connection.hub.url = "http://myip:56698";
$.connection.hub.qs = { 'UserId' : '35' };
var connection = $.hubConnection();
var hub = connection.createHubProxy('NotificationHub');
hub.on('Notify', function(userName, message) {
console.log(userName + ' ' + message);
});
connection.logging = true;
connection.start().done(function () {
console.log('Now connected, connection ID=' + connection.id);
})
.fail(function (a)
{
console.log('Could not connect'+ a );
});
}
While debugging using chrome, it comes to connection.start and does not go in to success or fail.Just leaves the script.There is no sign that it has connected to the server.
It has to hit OnConnected on server right?
Wondering whether i have missed something.
The above client code is all i did on the client project (apart from installing signalr.client package.) Thats enough right?
I want to know how to define the subscriber path.
For instance, declaration of subscribing path
stompClient.subscribe("/topic/simplemessagesresponse", function(servermessage) {
Why there are two parts 'topic' and 'simplemessageresponse' .. what they refere. How many such domain parts can be there and why ? My question is on not only for the client side, but also server side . SimpMessagingTemplate.convertAndSend("/topic/simplemessagesresponse", "Message to client");
There are tutorials showing the websocket server and client samples. But no enough details of rules to declare the subscriber path and how the subscriber path could be found.
What are the dependencies to change the path when it is declared in server and client side. I think another similar question is raised because of the a location change of a page where the websocket client is written.
Quoting the STOMP spec documentation:
Note that STOMP treats this destination as an opaque string and no
delivery semantics are assumed by the name of a destination. You
should consult your STOMP server's documentation to find out how to
construct a destination name which gives you the delivery semantics
that your application needs.
That means that destination semantics is broker specific:
For RabbitMQ: check out the Destinations section under the STOMP
plugin documentation- http://www.rabbitmq.com/stomp.html For
For ActiveMQ: check out the Working with Destinations with Stomp -
https://activemq.apache.org/stomp.html
I have implemented the websocket stomp by following this blog.
I replaced #SendTo by SimpMessagingTemplate.
Here is my sample ChatController
#Autowired
private SimpMessagingTemplate simpMessagingTemplate;
#MessageMapping("/dualchart")
#ResponseBody
public void dualchat(MessageDTO message) {
// forward message to destination
String destination = "/topic/dualchat/" + message.getToUser();
simpMessagingTemplate.convertAndSend(destination, message);
}
MessageDTO
#JsonIgnoreProperties
public class MessageDTO extends BaseModel {
private String fromUser;
private String toUser;
private String message;
public String getFromUser() {
return fromUser;
}
public void setFromUser(String fromUser) {
this.fromUser = fromUser;
}
public String getToUser() {
return toUser;
}
public void setToUser(String toUser) {
this.toUser = toUser;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Web Socket Config
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/dualchat">
<websocket:sockjs />
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic" />
</websocket:message-broker>
Javascript
var socket = new SockJS("/starter.web.admin/dualchat");
var stompClient = Stomp.over(page.socket);
stompClient.connect({}, socketJsConnectedCallback, socketJsErrorCallback);
function socketJsConnectedCallback() {
var myId = "111"; // replace this Id
stompClient.subscribe('/topic/dualchat/' + myId, function(message) {
console.log("you reveived a message::::::::::" + JSON.stringify(message));
// you have message, and you can do anything with it
});
}
function socketJsErrorCallback(error){console.log(error);}
function sendMessage(message) {
var data = {
toUser : "1",
message : message
}
stompClient.send("/app/dualchat", {}, JSON.stringify(data );
}
Hope this will help next search...