Winsock.SendData equivalent with Javascript? - javascript

Can the following VB Script to open an IP cash drawer be done in Javascript instead?
Private Sub CashDrawerConnect_Click()
Winsock1.Close
ipaddr = "192.168.2.5"
Winsock1.RemoteHost = ipaddr
Winsock1.RemotePort = 30998
Winsock1.Connect
Sleep 250
TxtOpStatus = "Connection to the cash drawer at " & ipaddr & " is established..."
TxtOpStatus.Refresh
End Sub
Private Sub CashDrawerOpen_Click()
If Winsock1.State = sckConnected Then
Winsock1.SendData "opendrawer\0a"
Else
TxtOpStatus = "Not connected to the device"
TxtOpStatus.Refresh
End If
End Sub

You could do it on javascript, but not while running on a browser.
You would need to install nodejs and run your js file directly from the console.
This is a small example that would connect you the the drawer and send the "opendrawer" command on your example:
var net = require('net');
var client = net.connect({port: 30998, host: "yourip"}, function() {
client.write("opendrawer\0a");
});
If however the server has access to the drawer the javascript code could just make a request to the server which would be on charge of opening the connection to the drawer and sending the payload (opendrawer).
If you use php you can take a look at the sockets documentation.

Using VB and JavaScript the calls are mostly the same, you just jhave to adapt it to the language. http://www.ostrosoft.com/oswinsck/oswinsck_javascript.asp
The following is a snippet that uses WinSock from JScript
var oWinsock;
var sServer = "192.168.2.5";
var nPort = 3098;
var bClose = false;
oWinsock = new ActiveXObject("OSWINSCK.Winsock");
// Hooking up handlers
WScript.ConnectObject(oWinsock, "oWinsock_");
oWinsock.Connect(sServer, nPort);
WScript.Echo("Invalid URL");
bClose = true;
function oWinsock_OnConnect() {
oWinsock.SendData('Your data');
}
function oWinsock_OnDataArrival(bytesTotal) {
var sBuffer = oWinsock.GetDataBuffer();
sSource = sSource + sBuffer;
}
function oWinsock_OnError(Number, Description, Scode, Source,
HelpFile, HelpContext, CancelDisplay) {
WScript.Echo(Number + ': ' + Description);
}
function oWinsock_OnClose() {
oWinsock.CloseWinsock();
WScript.Echo(sSource);
oWinsock = null;
bClose = true;
}
while (!bClose) {
WScript.Sleep(1);
}
In the browser? Not really, but you can use WebSockets http://en.wikipedia.org/wiki/WebSocket
You'll need to implement a WebSocket server, so if you need to talk directly to a socket, you can't do it from a browser. But you could implement a proxy server that relays information between the socket server and the WebSocket server.
If you don't need two way communication, the best thing would be for your server to provide a webservice that wraps that socket request. Then your client can just make an AJAX call.

Related

WebSocket connection to 'ws://(server ip)/socket.io/?EIO=4&transport=websocket&sid=52ViP_GqPGSr4DkqAAAN' failed:

I have been trying to figure out this error for a few days. When I try to emit a socket from the client side (JS) to the server (Python - flask) I get the error of connection failed. However, this error isn't always consistent. If the error does happen, it will normally happen on the first time I try to emit the socket and it normally works after that. Also, I am having some trouble with mobile devices receiving events as well. I also have an nginx reverse proxy on my server as well.
When I run this on local host I do not get the error of WebSocket connection failing.
Client side:
function formsubmitted(){
var name = document.getElementById("startexampleInputEmail1").value
var pin = document.getElementById("startexampleInputGamePin").value
var predictions = document.getElementById("startexampleInputPredictions").value
var joinmsg = document.getElementById("startexampleInputJoinMsg").value
socket.emit("AccountCreation",[socket.id,name,pin,predictions,joinmsg])
}
Server side:
#socketio.on("AccountCreation")
def handle_new_acc(data):
sid = data[0]
name = data[1]
pin = data[2]
predictions = data[3]
joinmsg = data[4]
canCreateAcc = True
gameExists = False
for user in User.query.all():
if user.name == name:
canCreateAcc = False
emit("UsernameTaken",to=sid)
return
for game in Game.query.all():
if game.pin == pin:
gameExists = True
if gameExists == False:
emit("GameNotFound",to=sid)
if gameExists == True and canCreateAcc == True:
usertoadd = User(name,pin,predictions,joinmsg,1,"0 seconds","0 seconds",0,"")
db.session.add(usertoadd)
db.session.commit()
game = Game.query.filter_by(pin=pin).first()
player_list = json.loads(game.players)
player_list.append(name)
game.players = json.dumps(player_list)
db.session.commit()
emit("AccountReady",[name,pin,predictions,joinmsg],to=sid)
There may be a problem with your nginx configuration. Just recently I had a similar issue (although the connections failed all the time, not just sometimes), see if some of it helps: Websocket failed: flask app with nginx and gunicorn, react frontend with socket.io

Is there any way to implement real time messaging web application (Push message to the client among multiple clients)? [duplicate]

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/

Send cloud to device messages from Azure Function to device via IoT hub

Could you help me with the Java code which I use in a Function App?
IoT Hub which built endpoint is used as an IoT Hub(event hub) for a Function App is receiving telemetry from a device. By the following function, I extract values from the message received, process them and put in a CosmoDsB once the IoT Hub build endpoint has gotten a message from the device!
The main problem is that i need to send every processed value of the "totalLevel" variable back to the device via IoT Hub.
Once again : the entire structure is an "OPC server (MQTT)" <-/-> "IoT Hub" -"build endpoint IoT Hub" - "Function APP" -> back to the device.
C2D
I have not found any simple example how to do this in Java as an addition to the
existing function. Does anybody know any easy way to do this?
I found these examples but don't have enough skills to modify it.
https://learn.microsoft.com/en-US/azure/iot-hub/quickstart-send-telemetry-java
https://learn.microsoft.com/en-US/azure/iot-hub/iot-hub-java-java-c2d
thank you in advance
module.exports = function (context, IoTHubMessages) {
context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessages}`);
IoTHubMessages.forEach(message => {
context.log(`Processed message: ${message}`);
});
context.done();
};
module.exports = function (context, IoTHubMessages) {
context.log(`JavaScript eventhub trigger function called for message array:
${IoTHubMessages}`);
var count = 0;
var totalLevel = 0.0;
var totalHumidity = 0.0;
var deviceId = "";
IoTHubMessages.forEach(message => {
context.log(`Processed message: ${message}`);
count++;
totalLevel = message.L1 + message.L2 + message.L3;
RestartPLC = message.L4;
deviceId = message.deviceId;
});
var output = {
"deviceId": deviceId,
"PLC_Restart_state": RestartPLC,
// "measurementsCount": count,
"gemessener Gesamtabfluss, mm": totalLevel
//"averageHumidity": totalHumidity/count
};
context.log(`Output content: ${output}`);
context.bindings.outputDocument = output;
context.done();
};

Refresh webpage on change in folder

I want to refresh my web page every time a file is uploaded to the folder.
I have a web service written in flask having the following handler
#app.route('/getlatest/')
def getlatest():
import os
import glob
newset = max(glob.iglob('static/*'),key=os.path.getctime)
Return newest;
This gives me the name of the latest file in the folder.
I have an Ajax call in my JS (client side) to constantly get data from above function.
function GetLatest()
{
$.ajax({
url: "http://localhost:5000/getlatest",
success: function(result)
{
if(previousName != result){
previousName = result;
$("#image").attr("src","/"+previousName);
}
}
});
}
function calling server every second.
(function myLoop (i) {
setTimeout(function () {
GetLatest();
if (--i) myLoop(i);
}, 1000)
})(100);
This Works fine [well almost].
My Question is: Is there any better way to do it[ there must be ]?
i'm open to technology choices what every they may be [node, angualr etc.]
yea you can use websockets(flask-socketio).That will let you to have an open connection between you and server and every time in the folder is a new photo will be displayed on a selected div
http://flask-socketio.readthedocs.io/en/latest/
https://pypi.python.org/pypi/Flask-SocketIO/2.9.1
So here is how i did it.
first of all thanks to
https://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent
for explaining it perfectly.
What i have learnt reading a couple of blogs.
All communication initiated using http protocol is client server communication, and client is always the initiator. So in this case we have to use a different protocol: Web-sockets which allow you to create a full-duplex (two way) connection.
Here is the server code;
socketio = SocketIO(app, async_mode=async_mode)
thread = None
prevFileName = ""
def background_thread():
prevFileName = ""
while True:
socketio.sleep(0.5)
if(isNewImageFileAdded(prevFileName) == "true"):
prevFileName = getLatestFileName()
socketio.emit('my_response',
{'data': prevFileName, 'count': 0},
namespace='/test');
def getLatestFileName():
return max(glob.iglob('static/*'),key=os.path.getctime)
def isNewImageFileAdded(prevFileName):
latestFileName = max(glob.iglob('static/*'),key=os.path.getctime)
if(prevFileName == latestFileName):
return "false"
else:
return "true"
Creating separate thread to keep the socket open. emit sends the msg to the client from server...
#socketio.on('connect', namespace='/test')
def test_connect():
global thread
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})
And here is Client Side.[replaced ajax call with the following code]
var socket = io.connect(location.protocol + '//' + document.domain + ':' +
location.port + namespace);
socket.on('my_response', function(msg) {
setTimeout(function(){ $("#image").attr("src","/"+msg.data)},1000)
});
Please correct me if i am wrong.

How Play Framework handle CloseEvent from WebSocket?

I am using Play Framework with WebSocket in Scala, and I try to accept with Actor.
If web server close the connection, the client can touch this by onClose in JS like this:
websocket.onclose = function (evt) { onClose(evt) };
But what about the server side?
If the client close the browser, can web server touch this close event?
def ws(userId: String) =
WebSocket.tryAcceptWithActor[String, String](request⇒
Future {
Right(out ⇒ Props(new WsActor(userId, out)))
})
class WsActor(val userId: String, val clientActor: ActorRef) extends Actor{
override def receive: Receive = ???
#throws[Exception](classOf[Exception])
override def preStart(): Unit = {
}
//when client close
//will call it
#throws[Exception](classOf[Exception])
override def postStop(): Unit = {
println("stop")
}
}

Categories