I'm using the following C# code to send a packet to a local port.
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
byte[] send_buffer = Encoding.ASCII.GetBytes("Test message");
sock.SendTo(send_buffer, endPoint);
How can I do the same in a few calls in Actionscript? I don't need any two way communication or overhead: just as little code as possible to send a packet of text to a UDP server that I'm running in a C# app.
I've tried creating a javascript function to accept an ExternalInterface call and sending it on from Javascript with Node.js, but I think there might be an easier way of doing it.
//FLASH
ExternalInterface.call("sendToUDP", "Test message");
//HTML
<script language="JavaScript" type="text/javascript">
function sendToUDP(message)
{
//Some code to send a UDP packet from Javascript
}
</script>
Using DatagramSocket in AIR, this should be the equivalent AS3 to your C# code:
var socket:DatagramSocket = new DatagramSocket();
var address:String = "127.0.0.1", port:int = 9000;
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes("Test message");
socket.send(bytes, 0, 0, address, port);
Related
My goal is when I open a new browser(client), the message sent from the server in the previous client gets updated as well.
Currently,
The clients send messages to the server, the server stores them in localStorage as an array and should send it back to all the clients. All clients should get the same array of messages. It works like ajax call.
As of right now, when I open the first browser, the message is sent to the server and received in the client successfully, and then I open the second one(it works) but the message is not updated in the first browser. PS this acts like a forum, when somebody posts a messages to server, all users should be able to see it.
Here's my code for server:
<html>
<head>
<!-- This is the websocket SERVER -->
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
</head>
<body>
<div id="msg"></div>
<script>
// connect to WEBSOCKET server
var socket = io.connect('http://localhost:5000',{'forceNew':true} );
// Fire an event (that the server will handle
socket.emit('myEvent', 'Hello Message from the client');
// Attach event handler for event fired by server
socket.on('server', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML += "<br>" + data; // append data that we got back
});
</script>
</body>
</html>
Here's for client:
//---------------------------------------------------------------
// The purpose is to introduce you to websockets
// This is a SERVER that is SEPARATE from the http server.
//
// Your webpage (in this case the index.html in this directory)
// will be SERVED by the http server. THEN, it will connect to the
// websocket server. Then - they will talk to each other!
//
// Note that in regular http - the server cannot initiate a conversation
// Here, the websocket server sends a message to the client browser.
//
// This example has THREE parts
// 1) The http server code (which is same as what we did earlier)
// 2) This code - this is the web socket server
// It prints what it got from client. It also sends a message to the
// client after every 1 second.
// 3) The html or client code. Note how it connects to the websocket
// and how it sends and receives messages
//
// To RUN THIS EXAMPLE
// First, run node httpServer.js on one terminal
// Next, run node 1_ws.js on another terminal
// Next, type localhost:4000/index.html on some browser
//
//---------------------------------------------------------------
var items=[];
var io = require('socket.io').listen(5000);
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
}
io.sockets.on('connection', function(socket) {
socket.on('myEvent', function(content) {
//i need to store the content
items.push(content);
localStorage.setItem("list",JSON.stringify(items));
socket.emit('server', JSON.parse(localStorage.getItem("list")));
});
});
I'm running on the local server:( you can ignore the local server if you want, the above code can function on their own)
//---------------------------------------------------------------
// The purpose is to serve a file!
//---------------------------------------------------------------
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var server = http.createServer();
// attach handler
server.on('request', function (req,res) {
var file = path.normalize('.' + req.url);
fs.exists(file, function(exists) {
if (exists) {
var rs = fs.createReadStream(file);
rs.on('error', function() {
res.writeHead(500); // error status
res.end('Internal Server Error');
});
res.writeHead(200); // ok status
// PIPE the read stream with the RESPONSE stream
rs.pipe(res);
}
else {
res.writeHead(404); // error status
res.end('NOT FOUND');
}
});
}); // end server on handler
server.listen(4000);
console.log("start");
You are sending response to only client who sent message to sever only,
To send to all clients which are connected you must use this,
io.emit('server', JSON.parse(localStorage.getItem("list")));
Visit this answer for all
Responses
I need to convert a csv file to json format and send it to a client requesting to ws server in nodejs ,
the file will be updated so many times so i need to send updated data to client
i am able to send data once it is loaded completely(like when app is started it sends all data in file to client) but when i update data in the file the updated data is being printed out on console but it is not being sent to client is their any thing wrong in my code
my node.js code:
var ts = require('tail-stream');
var Converter = require("csvtojson").Converter;
var converter = new Converter({constructResult:false}); //for big csv data
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets server
// we don't have to implement anything.
response.write('hello');
console.log('in http server \n');
});
server.listen(1337, function() { });
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
console.log('wsserver');
connection.send('ws server');
converter.on("record_parsed", function (jsonObj) {
console.log(jsonObj); //here is your result json object
connection.send(jsonObj);
});
var tstream = ts.createReadStream('log.csv', {
beginAt: 0,
onMove: 'follow',
detectTruncate: false,
onTruncate: 'end',
endOnError: false
});
tstream.pipe(converter);
});
Right now you are creating a new read stream and adding a listener to the converter on every new connection, that will cause trouble once you have more than one client (same event emitted multiple times, etc..). Instead of that you should keep just one reader and notify all open connections when there's a new record.
Also notice that the library you are using only accepts UTF-8 strings or binary type messages, row objects sent the way you're sending them now will be received as a "[object Object]" string after toString() is called on them. You should probably send just send the row string or use JSON.stringify / JSON.parse.
Try this:
var http = require("http");
var tailStream = require("tail-stream");
var Converter = require("csvtojson").Converter;
var WebSocketServer = require("websocket").server;
var server = http.createServer();
var wsServer = new WebSocketServer({ httpServer: server });
var converter = new Converter({constructResult:false});
var logStream = tailStream.createReadStream("log.csv", { detectTruncate : false });
var connections = [];
server.listen(1337);
logStream.pipe(converter);
//----------------------------------------------------
converter.on("record_parsed", function (jsonObj) {
connections.forEach(function(connection){
connection.send(JSON.stringify(jsonObj));
});
});
//----------------------------------------------------
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
connection.on("close", function() {
connections.splice(connections.indexOf(connection), 1);
});
connections.push(connection);
});
The code above works, tested like this on the client side:
var socket = new WebSocket('ws://localhost:1337/');
socket.onmessage = function (event) {
console.log(JSON.parse(event.data));
}
Note: this doesn't send the whole content of the file at the beginning, just the updates, but you can easily achieve this storing the records and sending them on new connections.
I have a server I wrote in NodeJs which listens to port 1234.
From my client (html) I want to send request to my server and wait for an answer.
I tried to use XMLHttpRequest:
var http = new XMLHttpRequest();
var url = "127.0.0.1:1234";
var params = "token=22";
http.open("post", url, true);//"https://www.google.com/search?q=asd"
http.setRequestHeader("Content-type", "text/html");
http.setRequestHeader("Content-length", 0);
http.setRequestHeader("Connection", "keep-alive");
http.onreadystatechange = function() {//Call a function when the state changes.
alert(http.responseText);
}
http.ontimeout = function()
{
alert("timeout");
}
http.timeout=10;
try
{
http.send(null);
}
catch(ex)
{
alert(ex);
}
But I always got exception. The reason was I can't use my own port.
Is There any other way to send request and get respond?
There is nothing wrong with using JQuery.ajax to make your life easier and it does get a lot easier with jquery especially when it comes to XMLHttpRequest.
I'm new to WebSockets. I read a lot of info on the subject and i'm trying to build a simple server just to handle the handshake part, but still can't get my server to work properly. The client sends the request, the server sends a response back to the client, but it won't fire the onopen event for the WebSocket. But if I close the server, the websocket object fires it's onclose event.
The request I get from chrome is:
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 192.168.0.164:3215
Origin: http://lalala
Sec-WebSocket-Key: MyUY7duPdE1WbGXPOslYzw==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
The response I send back:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 4IVZgO4OosW/b7upp7Qbh2q6a4I=
The code i'm using in the server:
static void Main(string[] args)
{
var listener = new TcpListener(IPAddress.Parse("192.168.0.164"), 3215);
listener.Start();
Console.WriteLine(">> Started.");
var client = listener.AcceptTcpClient();
Console.WriteLine(">> Accepted.");
while (true)
{
try
{
var stream = client.GetStream();
var bytes = new byte[client.ReceiveBufferSize];
stream.Read(bytes, 0, client.ReceiveBufferSize);
var data = Encoding.ASCII.GetString(bytes);
Console.WriteLine(data.Remove(data.IndexOf("\0\0\0")));
var code = data.Remove(0, data.IndexOf("Sec-WebSocket-Key:") + 19);
code = code.Remove(code.IndexOf("==") + 2);
var response = string.Format(#"HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: " + GetServerResponseKey(code));
Console.WriteLine(response);
var encodedResponse = Encoding.UTF8.GetBytes(response);
stream.Write(encodedResponse, 0, encodedResponse.Length);
}
catch (IOException)
{
Console.WriteLine(">> Client Disconnected.");
Console.ReadKey();
return;
}
}
}
private static string GetServerResponseKey(string key)
{
var keyForHash = String.Concat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
var encoding = new UTF8Encoding();
var temp = encoding.GetBytes(keyForHash);
var hashProvider = new SHA1CryptoServiceProvider();
var keyForBase64 = hashProvider.ComputeHash(temp);
return Convert.ToBase64String(keyForBase64);
}
And the client script:
<script type="text/javascript">
var socket;
function connect()
{
socket = new WebSocket('ws://192.168.0.164:3215');
setTimeout(bindEvents, 1000);
setReadyState();
}
function bindEvents() {
socket.onopen = function() {
alert('handshake successfully established. May send data now...');
setReadyState();
};
socket.onclose = function() {
alert('connection closed');
};
}
function setReadyState() {
console.log('ws.readyState: ' + socket.readyState);
}
connect();
</script>
Some more questions:
1-Is there a way that I can find out which protocol my browser uses?
2-Which protocol Chrome 21 uses?
Your response needs to follow the rules for HTTP request/responses and have a carriage return + line feed between each header and a pair at the end. Instead of using new lines in the response I would escape encode them:
"header1\r\nheader2\r\nheader3\r\n\r\n"
The "Sec-WebSocket-Version: 13" header indicates that the browser is using version 13 of the protocol which is IETF 6455.
can someone please suggest way to communicate between Air(Action script) App and node.js server?
e.g.
Communication between PHP and Flash(Action Script) application using AMFPHP
BlazeDS for Java+Adobe Flex and Adobe Integrated Runtime (AIR)
Please send me your suggestions, any tutorial, or PoC sample code
Thanks in Advance.
Here is a sample I wrote for a blog. I think the code itself pretty much explains itself.
Client Side AS3 Code :
var urlString:String = "http://localhost:1337/";
function Submit():void
{
var requestVars:URLVariables = new URLVariables();
requestVars.Username = "guest";
var request:URLRequest = new URLRequest();
request.url = urlString;
request.method = URLRequestMethod.GET;
request.data = requestVars;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
try { loader.load(request); }
catch (error:Error) { // Handle Immediate Errors }
}
function loaderCompleteHandler(e:Event):void
{
trace(e.target.data); // Response Text
}
Brief about the code snippet:
We fill in the request data by instantiating a URLVariables class as
requestVars.
We fill in the url & method by instantiating URLRequest class as request.
We attach an load complete event Handler to handle the response.
Wrapping up for catching errors, we call the load method.
URL is set to Localhost port 1337 where the nodeJS would be hosted.
The variable set is a test field UserName which is checked for in the server script.
Server Side NodeJS Code :
var http = require('http'), url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var urlObj = url.parse(req.url, true);
if(urlObj.query["Username"] == "guest") res.end("True");
else res.end("False");
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Brief about the code snippet:
The code listens at port 1337 in the localhost server where it is hosted.
The query string is unwrapped to get the UserName variable & tested.
Server Responds with true since the value equates to guest.