notepad++ with node using sockets error - javascript

Im trying to send a message from a webpage to a node server. Im using notepad++. My html looks likes this:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<script>
function one()
{
var socket = io.connect('http://192.168.201.91:8001');//connect the socket to url
socket.emit('Stream', {"StreamName": "Livestream1"});//send the socket with the parameter and data
}
</script>
</head>
<body>
</br>
</br>
<center><button type ="Button" onclick="one()">Stream name 1</button></center>
</body>
</html>
These are supposed to connect to a node server which is on the given address.
In node I have set up the sockets like this:
var io_client = require('socket.io').listen('8001');
io_client.on('Stream', function(data)
{
var name = data;
console.log(data);
});
Do I need to use socket.io-client for this to get a message from the html to the server and the server to listen??
Any help would be great

There were two problems in your question.
1.) Use latest version of socket-io client. Older leads to bad request error. use following
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
2.) your code in server should be like this.
var server = require('socket.io').listen('8001');
server.on('connection',function(socket){
console.log('connection');
socket.on('Stream', function(data){
var name = data;
console.log(data);
});
});
You were expecting the Streams event on server itself. But it'll occur on that socket from where it has been sent.

Related

protobuf.js using CommonJS?

I am relatively new to JS but very familiar with protobuf. I'm currently designing a web page hosted from a Java HTTP server, and would like to implement protobuf communication between them.
My issue is on the browser side. After some research I found the protobuf.js git page and attempted to use this within my javascript. I ran into issues firstly getting the module over HTTP because
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.js"></script>
uses text/plaintext and fails to return. Adding a type=text/javascript just led to protobuf is not defined.
I then tried to take the project source into my web root, and directly use this:
<script type="text/javascript" src="./js/protobuf-js/src/index.js" ></script>
and:
import * as protobuf from "./js/protobuf-js/src/index.js";
This worked and the web server returned the file. Now, this is where my understanding reaches it's limits. From what I can tell from the README page on git, it distinctly says
"The library supports CommonJS and AMD loaders and also exports globally as protobuf."
If I look inside index.js I see the following:
var protobuf = module.exports = require("./index-light");
which throws a Module is not defined in ES module scope exception in browser.
Nowhere else online could I find working examples of the protobuf.js being used in commonJS as it states in the git, it all refers to Node.js which I don't want to use as i'm using Java for the webserver side of things.
Am i being really dumb and missing something obvious?
Thanks
There are example in https://github.com/protobufjs/protobuf.js.
a small example:
hello.proto
syntax = "proto3";
message Test{
string msg=1;
}
test.html
<html lang="en">
<head>
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.11.3/dist/protobuf.js"></script>
</head>
<body>
<script>
function test(){
protobuf.load("hello.proto", function(err, root) {
var TestMsg = root.lookup('Test');
var payload = {msg:'hello'};
var result = TestMsg.verify(payload);
if(result) throw Error(result);
var msg = TestMsg.create(payload);
var binMsg = TestMsg.encode(msg).finish(); // this is the binary protobuf message
// to handle blob data from server via websocket, you need handle like below
// event.data.arrayBuffer().then(buf =>{
// var msg = TestMsg.decode(new Uint8Array(buf));
// }
// deserialize
var msg2 = TestMsg.decode((binMsg));
console.log(msg2.toJSON());
alert(msg2.msg);
});
}
</script>
<input type="button" value="test" onclick="test()">
</body>
</html>

How to communicate with python server from web browser?

I'm trying to send basic commands to a robot from a webbrowser.
The robot is connected to my network and it is running a simpleXMLRPC server as below:
import socket
from xmlrpc.server import SimpleXMLRPCServer
message = []
def py_setMsg(msg):
#global message
message.append(msg)
return "check"
def py_getMsg():
if len(message) > 0:
temp = str(message[-1])
message.pop(-1)
return temp
else:
return "(no message)"
hostname = socket.gethostname()
host = socket.gethostbyname(hostname)
port = 60050
server = SimpleXMLRPCServer((host, port))
server.register_function(py_setMsg, "ext_setMsg")
server.register_function(py_getMsg, "ext_getMsg")
print("XMLRPC Server started..")
server.serve_forever()
My robot checks the messages in the message list and executes the commands in the list one by one.
What I want is to be able to add these commands from a web browser. So basically I want a command to be added to the list in my python server when a button is pressed, something like this:
<html>
<head>
</head>
<body>
<button type="button" onclick="setMessage()">klik hier</button>
<script>
function setMessage(){
send command to my python server
}
</script>
</body>
</html>
Can anyone tell me how I can achieve this?

Apache Thrift Javascript client to C++ Server [duplicate]

I have the following Thrift client code in javascript:
<script language="javascript" type="text/javascript" src="thrift.js" />
<script language="javascript" type="text/javascript" src="QuantSvc_types.js" />
<script language="javascript" type="text/javascript" src="QuantSvc.js" />
<script language="javascript" type="text/javascript">
function calc() {
var transport = new Thrift.Transport("http://localhost:9997/QuantSvc/");
var protocol = new Thrift.Protocol(transport);
var client = new QuantSvcClient(protocol);
try {
result = client.ListAllVariables()
} catch(ouch) {
alert("An exception occurred!")
}
}
</script>
Which is triggered when I push a button on my HTML page. Then, I have the following server-side Scala code, running on localhost:9997:
object Application extends App {
val handler = new QuantSvcHandler()
val processor = new QuantSvc.Processor(handler)
val serverTransport = new TServerSocket(9997)
val server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor))
}
Where the QuantSvcHandler's ListAllVariables function is (basically a skeleton function, just trying to get things to work):
override def ListAllVariables(): util.List[Attributes] =
{
var input = scala.collection.mutable.Buffer[Attributes]()
input
}
I put a breakpoint at the first line of ListAllVariables, and also a few places in the QuantSvcHandler processor. I run the server in debug in intellij IDEA, open my HTML page in Chrome, and push the button (the one that calls the javascript calc() function). The button stays stuck and I see no kind of response on the server, the breakpoints aren't being hit.
Any ideas about what I'm doing wrong?
You mix a HTTP client with a socket server.
Although HTTP uses sockets, the Thrift HTTP transport is not compatible with the Thrift Sockets transport. You need to set up the exact same protocol/transport stack on both ends. The only exception to that rule is that some server transports implicitly require an additional framed transport layer on the client side.
So the solution is to use a HTTP server. Depending on the version you use, you may also have to switch to the JSON protocol.

Handling .js and .css in Node.js

I'm trying to create a simple chat application with node.js and jQuery but I'm getting an error in my console saying '$ is not defined'. I'm following a tutorial where the authr is using jquery without a problem.
My chat.js (the server):
var http = require('http'),
sys = require('sys'),
fs = require('fs'),
ws = require('./ws.js');
var clients = [];
http.createServer(function(req,res){
res.writeHead(200,{
'Content-Type': 'text/html'
});
var rs = fs.createReadStream(__dirname + '/test.html');
sys.pump(rs, res);
}).listen(4000);
ws.createServer(function(websocket){
websocket.on('connect', function(resource){
clients.push(websockets);
websocket.write('Welcome');
});
websocket.on('data', function(data){
clients.forEach(function(client){
client.write(data);
});
});
websocket.on('close',function(){
var pos = clients.indexOf(websocket);
if(pos >= 0){
clients.splice(pos, 1);
}
});
}).listen(8081);
test.html (the client):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
ws = new WebSocket("ws://localhost:8080");
ws.onmessage = function(event){
var data = data.replace(/&/g, "&").replace(/</g,"<").replace(/>/g,">");
$('#log ul').append('<li>' + data + '</li>');
}
});
</script>
</head>
<body>
<div id="log"><ul></ul></div>
<div id="console">
<input type="text" id="entry"/>
</div>
</div>
</body>
</html>
I was getting errors before I stripped out all the .css and other .js src so I'm pretty sure the problem is with the 'Content-Type' code in the server.
I suspect the problem is that you are not serving jquery-1.7.2.min.js from your server, so the web page is not loading jquery, hence no $. First, try referencing a hosted jquery and see if that fixes your problem.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Although not totally relevant to your problem, if you are building a public website, then it is generally a good idea to reference hosted jquery (and other libs) as your users will probably have a locally cached copy already (thanks to other sites which did the same thing). See http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/ for a reasonable explanation of this.
Generally, though, you are going to want to serve some static files: your own css and js, images and the like. There are --plenty--of--posts-- describing how to do this longhand with node, but you may want to look at a dedicated module like this: https://github.com/cloudhead/node-static
On the server side, the code you are using is very old. sys.pump has been deprecated for at least over a year.
I'd advise you to read the examples from socket.io. There happens to be a chat server as well in the examples.
Who's serving your static files? From the code you have, it looks like the only static file you're serving is the HTML page.
You need to add some code to handle all static files at a specific location. Basically, you need to handle all static files within your
http.createServer(function() {...})
See: http://www.sitepoint.com/serving-static-files-with-node-js/

configure log4javascript to struts web application

How can we write the JavaScript info and error messages to the log file using log4j.
Please find the code below
<script type="text/javascript" src="././scripts/log4javascript.js"></script>
<script type="text/javascript">
var log = log4javascript.getDefaultLogger();
log.removeAllAppenders();
log.addAppender("start logging");
</script>
function writetoLog()
{
log.info("Start the Script Log..");
}
<body onload="writetoLog();">Some html code here </body>
This info messages is not write to the my log file.
Please suggest
You need to create an AjaxAppender. It's covered in the documentation of log4javascript (for example, in the quick start tutorial: http://log4javascript.org/docs/quickstart.html).
var log = log4javascript.getLogger("server");
var ajaxAppender = new log4javascript.AjaxAppender("/yourapp/jslog.do");
log.addAppender(ajaxAppender);
log.debug("Testing server log");

Categories

Resources