1 (изменено: Xameleon, 2021-07-28 21:27:55)

Тема: WSH,JS: Пример использования WebSocket в WSH

Всем привет ! На днях пришлось собрать для одной из задач. Решил поделиться примером.


// Restarting the process to run it console mode
if(!/cscript\.exe/ig.test(WScript.FullName)){
	new ActiveXObject('WScript.Shell').Run('cmd /c chcp 1251 > nul & cscript //nologo "' + WScript.ScriptFullName + '" & pause',1);
	WSH.Quit();
}
// Creating WSH standard streams short links
	var	StdIn = WSH.StdIn,
	StdOut = WSH.StdOut,
	StdErr = WSH.StdErr,
	// HTML document creation
	document = new ActiveXObject('htmlfile');
// Initializing document as maximum available version
document.write('<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />');
// Getting window object link
var window = document.parentWindow,
	// JSON object
	JSON = window.JSON,
	// Getting WebSocket constructor
	WebSocket = window.WebSocket;
// Checking document mode version
if(document.documentMode < 10) throw new Error('Sorry, Your browser document mode is ' + document.documentMode + '. It doesn\'t support needed functionality !');
// Checking if needed objects are available
if(!JSON) throw new Error('Failed to get JSON object');
if(!WebSocket) throw new Error('Failed to get WebSocket constructor');
// Attaching error message
window.onerror = function(message, url, line, column, error){
	throw new Error([
		'HTML document script error',
		'message:\t' + message,
		'url:\t\t' + url,
		'line:\t\t' + line,
		'column:\t\t' + column,
		'error:\t\t' + error
	].join('\r\n'))
}
// Creating web socket
var url = 'wss://echo.websocket.org/';
StdOut.WriteLine('Opening web socket "' + url + '" ...');
var ws = new WebSocket(url);
// Attaching open event
ws.onopen = function(event){
	StdOut.WriteLine('Web socket opened !');
	sendMessage();
}
// Macro for sending messages
function sendMessage(){
	WSH.Sleep(100);
	StdOut.Write('Send message: ');
	ws.send(StdIn.ReadLine());
}
// Attaching web socket message event
ws.onmessage = function(event){
	StdOut.WriteLine('Web socket message: ' + event.data);
	sendMessage();
}
// Attaching web socket error event
ws.onerror = function(event){
	StdErr.WriteLine('Web socket error !');
}
// Attaching web socket close event
ws.onclose = function(event){
	StdOut.WriteLine('Web socket closed');
	WSH.Quit();
}
// Main loop for waiting events
while(-1){
	WSH.Sleep(100);		
}
Передумал переделывать мир. Пашет и так, ну и ладно. Сделаю лучше свой !