Git Product home page Git Product logo

flashsocket.io's Introduction

FlashSocket.IO

Flash library to facilitate communication between Flex applications and Socket.IO servers.

The actual websocket communication is taken care of by my fork of gimite/web-socket-js project.

This project wraps that and facilitates the hearbeat and en/decoding of messages so they work with Socket.IO servers

Checkout

Because this project makes use of git submodules you must make use of the recursive clone.

git clone --recursive git://github.com/simb/FlashSocket.IO.git

Building

Because this library is dependent on the websocket library, you must add the support/websocket-js path to you source path in flash builder or your build files.

Usage

For Socket.io 0.7 and 0.8 you will need to use the Beta swc that you can find in the downloads section. Currently in beta.

An example of a flex application connecting to a server on localhost is below

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   creationComplete="application1_creationCompleteHandler(event)">
	<s:layout>
		<s:VerticalLayout />
	</s:layout>
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import com.pnwrain.flashsocket.FlashSocket;
			import com.pnwrain.flashsocket.events.FlashSocketEvent;

			import mx.controls.Alert;
			import mx.events.FlexEvent;

			[Bindable]
			protected var socket:FlashSocket;

			protected function application1_creationCompleteHandler(event:FlexEvent):void
			{

				socket = new FlashSocket("localhost:8080");
				socket.addEventListener(FlashSocketEvent.CONNECT, onConnect);
				socket.addEventListener(FlashSocketEvent.MESSAGE, onMessage);
				socket.addEventListener(FlashSocketEvent.IO_ERROR, onError);
				socket.addEventListener(FlashSocketEvent.SECURITY_ERROR, onError);

				socket.addEventListener("my other event", myCustomMessageHandler);
			}

			protected function myCustomMessageHandler(event:FlashSocketEvent):void{
				Alert.show('we got a custom event!')	
			}

			protected function onConnect(event:FlashSocketEvent):void {

				clearStatus();

			}

			protected function onError(event:FlashSocketEvent):void {

				setStatus("something went wrong");

			}

			protected function setStatus(msg:String):void{

				status.text = msg;

			}
			protected function clearStatus():void{

				status.text = "";
				this.currentState = "";

			}

			protected function onMessage(event:FlashSocketEvent):void{

				trace('we got message: ' + event.data);
				socket.send({msgdata: event.data},"my other event");

			}

		]]>
	</fx:Script>
	<s:Label id="status" />
	<s:Label id="glabel" />
</s:Application>

flashsocket.io's People

Contributors

bwillard avatar catoc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flashsocket.io's Issues

I could not connect with the help of examples.

UPDATE. Delete old question.

With great difficulty I managed to connect only after I found the file app.js.
I also corrected some of the code the application to work.
protected function joinHandler(event:Event):void
{
socket.send("USERNAME:" + loginForm.username.text);
vs.selectedIndex = 1; //add this line
}
And change:
socket = new FlashSocket("localhost:9202"); //instead of "ws://localhost:9202/socket.io/flashsocket"

But I still cannot connect to exchange messages between clients. Each client sends a message to the server (this is seen in the log console), but it is not sent to all participants in the chat.

How can change app.js that massage will send all cliens?

Thank you.

Cannot connect using example. "Variable URLUtil not defined"

Need to use FlashSocket.IO without Flex. I am trying to just the fx:Script portion of the example in the README. This compiles fine, and connects to the server, but never handshakes. It throws this error: "Variable URLUtil not defined", when it tries to pull it it in the following lines from FlashSocket.as

var policyUrl:String = "xmlsocket://" + URLUtil.getServerName(wsUrl) + ":843";
return (URLUtil.getProtocol(this.callerUrl) + "://" +
URLUtil.getServerNameWithPort(this.callerUrl)).toLowerCase();

Client doesn't reconnect

When the server restarts, the client losses the connection and doesn't reconnect.
Since a disconnection event is not thrown, there is no way to know that the client disconnected and also if there was, it's unclear as to how to achieve a re-connection.

I've noticed that while connected is true (even if the server went down), webSocket.socket.connected is false (hence it is more accurate).

How can a re-connection be done using this library?

Thanks,
Ofir

cant seem to connect

i am very eager to try out flashsocket.io. after several attempts with 0.6 and also your 0.7 swc i cant seem to connect. i also tried different server implementations with different version of socket.io 0.6 and 0.7. the closest results i got were from your 0.7 alpha swc together with socket.io 0.7.11. flash connected but ended with a "client not handshaken client should reconnect" warning. on other 0.7 tries i got away with the "unknown transport: flashsocket" warning.

any ideas what could have been missing?

regards

feature requests: callbacks on event

Requesting callbacks on events, per our quick email exchange.

Here's how it works in node:

Client:

socket.emit('test', { an: "object", from: "the client" }, function(response) {
//do stuff with response, which == { an: "object", from: "the server" }
});

Server:

socket.on('test', function(message, callback) {
//do stuff with message, which == { an: "object", from: "the client" }
callback({ an: "object", from: "the server" });
});

support for 0.9

is 0.9 supported in the beta .swc as well?

where is the downloads section to get the beta.swc?

IWebSocketWrapper reference

Hey I've been trying to compile the FlashSocketDemo.mxml file that you have here and I keep getting this error: "Error: Interface IWebSocketWrapper was not found". Here's my compile command:

mxmlc M:(source_path)\FlashSocketDemo.mxml -library-path+=M:(source_path)\libs\as3corelib.swc

I went through the files and IWebSocketWrapper is only referenced in one file in FlashSocket.as on line 23: "public class FlashSocket extends EventDispatcher implements IWebSocketWrapper". Is that supposed to be referenced anywhere else? Or am I compliling it incorrectly? Thanks.

Darryl

Discovery error with restfiy and socket.io

Hi,

When i use
socket = new FlashSocket("localhost:8080/socket");
I get discovery error

Node snippet:
(In app.js)
app.get('/socket', socket.handle);
app.post('/socket', socket.handle);

app.listen(8080, function() {
console.log('%s listening at %s', app.name, app.url);
});

var io = require('socket.io').listen(app);
exports.io = io;

(In routes)
exports.handle = function (req, res, next) {
console.log('In Handle'); //doesn't print this
io.sockets.on('connection', function(client){
console.log('Connection establiished');
});

Routing works just fine but flash socket is not able to discover the location.

Please advice.

GOT ALERT! type=0

Randomly when connecting to an HTTPS/WSS host the following error is triggered:

GOT ALERT! type=0

Main Thread (Suspended)
com.hurlant.crypto.tls::TLSEngine/parseAlert
com.hurlant.crypto.tls::TLSEngine/parseOneRecord
com.hurlant.crypto.tls::TLSEngine/parseRecord
com.hurlant.crypto.tls::TLSEngine/dataAvailable

License?

Hi, my team would like to use this but we noticed there isn't a license included in the project. Would you mind posting an MIT or other simple open source license to this? Thanks.

Support for multibyte encodings

As we can see in our tests, multibyte data in Russian is not parsed by Flashsocket.io correctly. It's processed as a single byte encoding, therefore russian words sent from server as
"Ядерный перец"
accepted on the flash side as
"Яде�н�й пе�еѿ" (note 2 times more symbols).

In our project we've resolved this issue by using decodeURIComponent() instead of unescape() function in Flashsocket.as sources.

Access of undefined receiveEvents

Thank you very much for the code but I have a problem

line 88 in FlashSocket.as

the statement var event:Object = (e.target as WebSocket).receiveEvents(); (line 88 in FlashSocket.as), says "Access of undefined receiveEvents".

Please help

Support for Node v0.10.x

This library works great for socket.io v0.9 and node v0.8.x, but I've upgraded my node version and found that socket.io will stall after "handshake authorized".

In testing the demo code on Node v0.10.x, sending data over websockets appears to show that the data is being received by the server, but not as a message. Instead it appears in the debug as the following:

debug - flashsocket received data packet 3:::[Message goes here]

The client, on other hand, does not appear to receive anything from the server.

Any ideas why this might be the case or how one might go about solving this issue?

corossdomain not loaded =(

Hi! How to achieve load policyUrl?

CLIENT

this.client.init(*************, 3004,null, function():void{
            client.addEventListener(ClientEvent.IO_ERROR,onError);
            client.addEventListener(ClientEvent.SECURITY_ERROR,onError);
            client.addEventListener(ClientEvent.MESSAGE,onMessage);
            Log("Connected ");
            dispatchEvent(new Event(Event.CONNECT));

});

SERVER DEMON ON NODEJS

var net = require('net');

console.log("Secur server started");


var host = '***********';
var port = 843;

var server = net.createServer(function(stream) {
stream.setEncoding('utf8');
stream.on('error', function (extension) {  console.log('policy.socket.error '+extension);  stream.end();        stream.destroy(); });
stream.on('connect',function(){console.log("Connected"); });
stream.on('end', function(){console.log("DISConnected"); stream.end();});
stream.addListener('data', function(mess) {
    var polic = '<?xml version="1.0"?>';
        polic += '<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">';
        polic += '<!-- Policy file for xmlsocket://socks.mysite.com -->';
        polic += '<cross-domain-policy>';
        polic += '    <allow-access-from domain="*" to-ports="*" />';
        polic += '</cross-domain-policy>\0';
    stream.write(polic);
    console.log('Conn :: policy, ip: '+stream.remoteAddress);
});

});

server.listen(port, host);

Can't connect. Connected Event never fires.

I created new project and link to as3corelib.swc, FlashSocket.IO-0.7.x-Beta_1.swc, and WebSocket.swc.
I added sample code from README file. Tried using socket.io 8 and socket.io 7
I am using Flash CS5.5. I have noticed that if I run in debug mode it connects. Seems something is happening to fast and doesn't handshake properly.

-- I keep getting this message on the server:
info - socket.io started
debug - setting request GET /socket.io/1/flashsocket/1306369664936810977
debug - set heartbeat interval for client 1306369664936810977
debug - flashsocket writing 7:::1+0
warn - client not handshaken client should reconnect
info - transport end
debug - set close timeout for client 1306369664936810977
debug - cleared close timeout for client 1306369664936810977
debug - cleared heartbeat interval for client 1306369664936810977
debug - discarding transport

-- On the Client Side this is my output
webSocketLog: policy file: xmlsocket://dev.bigstar.tv:843
webSocketLog: connected
webSocketLog: request header:
GET / HTTP/1.1

Upgrade: WebSocket

Connection: Upgrade

Host: localhost:1935

Origin: flash.swf://undefined:undefined

Cookie:

Sec-WebSocket-Key1: A1 VO 96 &68 21X 3 5 4g=

Sec-WebSocket-Key2: # 16 m jd B 8 52 920- k

webSocketLog: sent key3: lY@Ù©H�?
webSocketLog: closed

-- server Code
var http = require('express'),
io = require('socket.io'),
sys = require('sys');

// socket.io
var socket = io.listen(1935, {transports:['websocket', 'flashsocket', 'xhr-polling']});

// Add a connect listener

socket.on('connection', function(client){

var interval = setInterval(function() {
  client.send('This is a message from the server!  ' + new Date().getTime());
},5000);
// Success!  Now listen to messages to be received
client.on('message',function(event){
  console.log('Received message from client!',event);
client.send('Echo: ' + event );
});
client.on('disconnect',function(){
  //clearInterval(interval);
  console.log('Client has disconnected');
});

});

Node v0.10.x / Socket.io 0.9 do not work

Hi,

i'm trying to setup FlashSocket.IO but i never receive "connect" event.

This is the Debug:
info: handshake authorized RABQ67ORVyDDcCLbUP7x
debug: setting request GET /socket.io/1/flashsocket/RABQ67ORVyDDcCLbUP7x
debug: set heartbeat interval for client RABQ67ORVyDDcCLbUP7x
debug: client authorized for
myAppSay: "connection received" // console.log("connection received");

debug: emitting heartbeat for client RABQ67ORVyDDcCLbUP7x
debug: set heartbeat timeout for client RABQ67ORVyDDcCLbUP7x
debug: fired heartbeat timeout for client RABQ67ORVyDDcCLbUP7x
info: transport end (heartbeat timeout)
debug: set close timeout for client RABQ67ORVyDDcCLbUP7x
debug: cleared close timeout for client RABQ67ORVyDDcCLbUP7x
debug: discarding transport

Problem with transfer the project to a hosting

I created a simple project of realtime game using this lib. Everything works fine on my PC (localhost). Temporarily place the project on a free hosting cloudno.de. Did not work.

I use these files: server.js - file server nodejs (this file has not changed for hosting, because this port (8275) was nominated my application by hosting):

var io = require('socket.io'),
http = require('http');

var fs = require('fs'),
util = require('util');

var url = require('url'),
path = require('path'),
mime = require('mime');

function findType(uri) {
var ext = uri.match(/.\w+$/gi);
if (ext && ext.length > 0) {
ext = ext[0].split(".")[1].toLowerCase();
return mime.lookup(ext);
}
return undefined;
}

function sendError(code, response) {
response.writeHead(code);
response.end();
return;
}

var app = http.createServer(function(request, response) {
  var uri = url.parse(request.url).pathname;
  if (uri === '/') {
    uri = '/index.html';
  } else if (uri === '/server.js') {
    sendError(404, response);
    return;
  }
  var _file = path.join(process.cwd(), uri);

  path.exists(_file, function(exists) {
    if (!exists) {
      sendError(404, response);
    } else {
      fs.stat(_file, function(err, stat) {
        var file = __dirname + uri,
            type = findType(uri),
            size = stat.size;
        if (!type) {
          sendError(500, response);
        }
        response.writeHead(200, {'Content-Type':type + "; charset=utf-8", 'Content-Length':size});
        console.log("START");
        var rs = fs.createReadStream(file);
        util.pump(rs, response, function(err) {
          if (err) {
            console.log("ReadStream, WriteStream error for util.pump");
            response.end();
          }
        });
      });
    }
  });

});

var socket = io.listen(app, {transports:['websocket', 'flashsocket', 'xhr-polling']}),
buffer = [],
MAXBUF = 1024,
json = JSON.stringify;

var clients = [];
clients.usernames = function(client) {
return client.username;
}

socket.sockets.on('connection', function(client) {
console.log("CONNECTED");
client.on('message', function(data) {
//skipped more line of code

client.on('disconnect', function() {
if (client.username) {
client.json.broadcast.send({announcement:(client.username)+' left game', id:(client.id)});
}
var pos = clients.indexOf(client);
if (pos >= 0) {
clients.splice(pos, 1);
}
});});

if (!module.parent) {
app.listen(8275);
console.log("Socket-Chat listening on port 8275.. Go to http://:8275");
}

index.html - the client file. Here are some of its code to connect Websocket.

<script src="/socket.io/socket.io.js" charset="utf-8"></script>
    <script type="text/javascript" src="web_socket.js" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8"> ``` // Set URL of your WebSocketMain.swf here: WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf"; // Set this to dump debug message from Flash to console.log: WEB_SOCKET_DEBUG = true; // Everything below is the same as using standard WebSocket. var ws; function init() { // Connect to Web Socket. // Change host/port here to your own Web Socket server. ws = new WebSocket("ws://myapp.cloudno.de");//on localhost i use "localhost:8275" and will be change before transfer // Set event handlers. ws.onopen = function() { output("onopen"); }; ws.onmessage = function(e) { // e.data contains received string. output("onmessage: " + e.data); }; ws.onclose = function() { output("onclose"); }; ws.onerror = function() { output("onerror"); }; } function onSubmit() { var input = document.getElementById("input"); // You can send message to the Web Socket using ws.send. ws.send(input.value); output("send: " + input.value); input.value = ""; input.focus(); } function onCloseClick() { ws.close(); } function output(str) { var log = document.getElementById("log"); var escaped = str.replace(/&/, "&").replace(//, ">").replace(/"/, """); // " log.innerHTML = escaped + "
" + log.innerHTML; } ``` </script>

Can you please tell whether I have changed the configuration for hosting? For reference, the server logs for hosting and for localhost. The difference is noticeable immediately, but it is not clear why this is happening.

Hosting console log:

27 Dec 09:19:49 - Cloudnode wrapped script starting (30128) at Tue Dec 27 2011 09:19:49 GMT+0100 (UTC)
[36minfo -[39m socket.io started 27 Dec 09:19:49 -
[INFO] Cloudnode listening on port: 8275 Socket-Chat listening on port 8275.. Go to http://:8275
START
START
START
START
[90mdebug -[39m served static content /socket.io.js
START
START
[90mdebug -
[39m client authorized
[36minfo -
[39m handshake authorized 1357476841432378537

Localhost console log:

C:\inetpub\wwwroot\14l>node server.js
info - socket.io started
Socket-Chat listening on port 8275.. Go to http://:8275
START
debug - served static content /socket.io.js
START
START
START
debug - client authorized
info - handshake authorized 3511308552126147045
debug - setting request GET /socket.io/1/flashsocket/3511308552126147045
debug - set heartbeat interval for client 3511308552126147045
debug - client authorized for
debug - flashsocket writing 1:: CONNECTED

After starting my application occurs handshake and everything stopped - the connection fails. I changed a lot of options - nothing helps.

I suspect that problem or socket.io (but I simply copied the module working with my computer), or Flash security policy. But how to use it in my particular case is not clear. Here is the module that should help (https://github.com/3rd-Eden/FlashPolicyFileServer), but how to integrate it into my project?

I would be very grateful for the clarification.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.