I was wondering if anyone could help me with a small issue I have, I am trying to identify each client with the Fleck web sockets library in .NET and with PHP
PHP:
if (isset($_POST['web_socket_username_submit'])) {
$_SESSION['web_socket_username'] = $_POST['web_socket_username'];
header("location: ");
}
if (!isset($_SESSION['web_socket_username'])) {
echo 'You need to select a username before continuing, this username will stick with you untill you clean your cache.<br>';
echo '<form name="webSocketUsernameForm" method="post">';
echo '';
echo '<input type="text" name="web_socket_username" placeholder="Username...">';
echo '<input type="submit" name="web_socket_username_submit" value="Continue">';
echo '</form>';
exit();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>websocket client</title>
<script type="text/javascript">
var start = function () {
var inc = document.getElementById('incomming');
var wsImpl = window.WebSocket || window.MozWebSocket;
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');
inc.innerHTML += "connecting to server ..<br/>";
// create a new websocket and connect
window.ws = new wsImpl('ws://localhost:8181/');
// when data is comming from the server, this metod is called
ws.onmessage = function (evt) {
inc.innerHTML += "Emulator: " + evt.data + '<br/>';
};
// when the connection is established, this method is called
ws.onopen = function () {
inc.innerHTML += 'Emulator accepted your connection.<br/>';
};
// when the connection is closed, this method is called
ws.onclose = function () {
inc.innerHTML += 'Emulator closed the connection.<br/>';
}
form.addEventListener('submit', function(e){
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
</head>
<body>
<form id="sendForm">
<input id="sendText" placeholder="Text to send" />
</form>
<pre id="incomming"></pre>
</body>
</html>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebSockets_Testing
{
using Fleck;
class Program
{
static void Main(string[] args)
{
FleckLog.Level = LogLevel.Debug;
var allSockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("ws://127.0.0.1:8181");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
Console.WriteLine(message);
allSockets.ToList().ForEach(s => s.Send("You: " + message));
};
});
var input = Console.ReadLine();
while (input != "exit")
{
foreach (var socket in allSockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
}
}
}
How would I identify a client without it being spoofed who it is?
One simple way to achieve this is to use socket.ConnectionInfo.Id which returns a unique GUID per socket.
Related
Good afternoon, I'm writing chat in Perl using Mysql and the Websocket protocol.
I am using the AnyEvent module and Protocol :: WebSocket.
I understand that it would be better to use Mojo or Node.js for this, but in my case it needs to be that way.
I receive data from Websocket, reverse and connect. The data entered in the input field also fits into the database.
My problem is that how can I now output this data to the web interface in real time.
#!/usr/bin/env perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::Handle;
use AnyEvent::DBI::MySQL;
use AnyEvent::Socket;
use Protocol::WebSocket::Handshake::Server;
use Protocol::WebSocket::Frame;
my $dbh = AnyEvent::DBI::MySQL->connect("DBI:mysql:chat:localhost", "admin", "admin",
{
mysql_enable_utf8 => 1,
PrintError => 0,
}) or die;
my $cv = AnyEvent->condvar;
my $hdl;
my $sth;
AnyEvent::Socket::tcp_server undef, 3000, sub {
my ($clsock, $host, $port) = #_;
my $hs = Protocol::WebSocket::Handshake::Server->new;
my $frame = Protocol::WebSocket::Frame->new;
$hdl = AnyEvent::Handle->new(fh => $clsock);
$hdl->on_read(
sub {
my $hdl = shift;
my $chunk = $hdl->{rbuf};
$hdl->{rbuf} = undef;
if (!$hs->is_done) {
$hs->parse($chunk);
if ($hs->is_done) {
$hdl->push_write($hs->to_string);
return;
}
}
$frame->append($chunk);
my $message = $frame->next;
if ($message eq ""){
$message = undef;
} else {
$sth = $dbh->do("INSERT INTO web_chat VALUES('$message')", { async => 0 });
}
my $ary_ref = $dbh->selectcol_arrayref("SELECT text FROM web_chat");
}
);
};
$cv->wait;
1;
Client is not written in Javascript
<!doctype html>
<form name="publish">
<input type="text" name="message" maxlength="50"/>
<input type="submit" value="Send"/>
</form>
<div id="messages"></div>
<script>
let socket = new WebSocket('ws://192.168.1.1:3000/websocket/');
// отправка сообщения из формы
document.forms.publish.onsubmit = function() {
let outgoingMessage = this.message.value;
socket.send(outgoingMessage);
return false;
};
socket.onopen = function () {
console.log("Websocket Connection");
};
socket.onerror = function () {
console.log("Error websocket connection ");
}
// прослушка входящих сообщений
socket.onmessage = function(event) {
let incomingMessage = event.data;
showMessage(incomingMessage);
};
socket.onclose = event => console.log(`Closed ${event.code}`);
// отображение информации в div#messages
function showMessage(message) {
let messageElem = document.createElement('div');
messageElem.textContent = message;
document.getElementById('messages').prepend(messageElem);
}
</script>
May I suggest Mojolicious and Mojo::Mysql for this?
Protocol::WebSocket is pretty “bare-bones” and doesn’t handle a lot of the protocol details like ping/pong.
I am developing a wpf application by using Xilium.CefGlue and Xilium.CefGlue.WPF. My WPF application is getting crashed after implementing Xilium.CefGlue.CefApp.GetRenderProcessHandler() in SampleCefApp. Before this implementation the application was working fine without any crashes. Actually I need to call a C# function from html local page by javascript function. This functionality is working fine in 32 bit version but not in 64 bit. The following is my implementation.
internal sealed class SampleCefApp : CefApp
{
public SampleCefApp()
{
}
private CefRenderProcessHandler renderProcessHandler = new Views.DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler()
{
return renderProcessHandler;
}
}
the following message was showing for app crash
<ProblemSignatures>
<EventType>APPCRASH</EventType>
<Parameter0>StreetMap.vshost.exe</Parameter0>
<Parameter1>14.0.23107.0</Parameter1>
<Parameter2>559b788a</Parameter2>
<Parameter3>libcef.DLL</Parameter3>
<Parameter4>3.2743.1449.0</Parameter4>
<Parameter5>57bbfe66</Parameter5>
<Parameter6>80000003</Parameter6>
<Parameter7>0000000000b68267</Parameter7>
</ProblemSignatures>
Is ther any issues for libcef dll while working with 64 bit. Is anybody can help for implementing JS to C# call by using Xilium.CefGlue and Xilium.CefGlue.WPF.
The following reference code i am using for this from the link
https://groups.google.com/forum/#!topic/cefglue/EhskGZ9OndY
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System;
namespace Xilium.CefGlue.Client {
internal sealed class DemoApp: CefApp {
private CefRenderProcessHandler renderProcessHandler = new DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler() {
return renderProcessHandler;
}
}
internal class DemoRenderProcessHandler: CefRenderProcessHandler {
MyCustomCefV8Handler myCefV8Handler = new MyCustomCefV8Handler();
protected override void OnWebKitInitialized() {
base.OnWebKitInitialized();
var nativeFunction = # "nativeImplementation = function(onSuccess) {
native
function MyNativeFunction(onSuccess);
return MyNativeFunction(onSuccess);
};
";
CefRuntime.RegisterExtension("myExtension", nativeFunction, myCefV8Handler);
}
internal class MyCustomCefV8Handler: CefV8Handler {
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue,
out string exception) {
//Debugger.Launch();
var context = CefV8Context.GetCurrentContext();
var taskRunner = CefTaskRunner.GetForCurrentThread();
var callback = arguments[0];
new Thread(() => {
//Sleep a bit: to test whether the app remains responsive
Thread.Sleep(3000);
taskRunner.PostTask(new CefCallbackTask(context, callback));
}).Start();
returnValue = CefV8Value.CreateBool(true);
exception = null;
return true;
}
}
internal class CefCallbackTask: CefTask {
private readonly CefV8Context context;
private readonly CefV8Value callback;
public CefCallbackTask(CefV8Context context, CefV8Value callback) {
this.context = context;
this.callback = callback;
}
protected override void Execute() {
var callbackArguments = CreateCallbackArguments();
callback.ExecuteFunctionWithContext(context, null, callbackArguments);
}
private CefV8Value[] CreateCallbackArguments() {
var imageInBase64EncodedString = LoadImage(# "C:\hamb.jpg");
context.Enter();
var imageV8String = CefV8Value.CreateString(imageInBase64EncodedString);
var featureV8Object = CefV8Value.CreateObject(null);
var listOfFeaturesV8Array = CefV8Value.CreateArray(1);
featureV8Object.SetValue("name", CefV8Value.CreateString("V8"), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isEnabled", CefV8Value.CreateInt(0), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isFromJSCode", CefV8Value.CreateBool(false), CefV8PropertyAttribute.None);
listOfFeaturesV8Array.SetValue(0, featureV8Object);
context.Exit();
return new [] {
listOfFeaturesV8Array,
imageV8String
};
}
private string LoadImage(string fileName) {
using(var memoryStream = new MemoryStream()) {
var image = Bitmap.FromFile(fileName);
image.Save(memoryStream, ImageFormat.Png);
byte[] imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
}
}
The HTML file, that I loaded at the first place:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>C# and JS experiments</title>
<script src="index.js"></script>
</head>
<body>
<h1>C# and JS are best friends</h1>
<div id="features"></div>
<div id="image"></div>
</body>
</html>
The JavaScript code:
function Browser() {
}
Browser.prototype.ListAllFeatures = function(onSuccess) {
return nativeImplementation(onSuccess);
}
function App(browser) {
this.browser = browser;
}
App.prototype.Run = function() {
var beforeRun = new Date().getTime();
this.browser.ListAllFeatures(function(features, imageInBase64EncodedString) {
var feautersListString = '';
for (var i = 0; i < features.length; i++) {
var f = features[i];
feautersListString += ('<p>' + 'Name: ' + f.name + ', is enabled: ' + f.isEnabled + ', is called from js code: ' + f.isFromJSCode + '</p>');
}
feautersListString += '<p> The image: </p>';
feautersListString += '<p>' + imageInBase64EncodedString + '</p>';
document.getElementById("features").innerHTML = feautersListString;
var afterRun = new Date().getTime();
document.getElementById("image").innerHTML = '<img src="data:image/png;base64,' + imageInBase64EncodedString + '" />';
var afterLoadedImage = new Date().getTime();
console.log("ELAPSED TIME - INSIDE LIST ALL FEATURES: " + (afterRun - beforeRun));
console.log("ELAPSED TIME - IMAGE IS LOADED TO THE <img> TAG: " + (afterLoadedImage - beforeRun));
});
}
window.onload = function() {
var browser = new Browser();
var application = new App(browser);
//Lets measure
var beforeRun = new Date().getTime();
application.Run();
var afterRun = new Date().getTime();
console.log("ELAPSED TIME - INSIDE ONLOAD: " + (afterRun - beforeRun));
}
Any help is appreciated.
I enabled the cef logging. It shows the following log
[0826/171951:ERROR:proxy_service_factory.cc(128)] Cannot use V8 Proxy resolver in single process mode.
.So I changed the SingleProcess=false in CeffSetting. Now the crashing issue is solved and then the requested webpage is not showing in cefwpfbrowser.
Now I am getting the following message from the log file
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(151)] 000000001B2A7CC0: set chrome proxy config service to 000000001B234F60
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(276)] 000000001B2A7CC0: Done pushing proxy to UpdateProxyConfig
[0826/173637:VERBOSE1:webrtc_internals.cc(85)] Could not get the download directory.
How to solve the requested page not loading issue in cefwpfbrowser.
I am a trying to make a small web server for testing. I made it with NodeJS. But something unexpected happened. The webpage passed by the NodeJS server couldn't be displayed properly. But the webpage worked perfectly when I used php+Apache. When I opened the source code received at my client side, there are no observable difference. Here is my code:
Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];
var server = http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(port);
console.log('Server running at http://127.0.0.1:8081/');
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
socket.setTimeout(4000);
});
function anyOpen(array) {
for (var ele in array) {
if (ele) return true;
}
return false;
}
(function countDown (counter) {
console.log(counter);
if (anyOpen(sockets)) {
return setTimeout(countDown, 1000, Max);
} else if (counter > 0 ) {
return setTimeout(countDown, 1000, counter - 1);
};
server.close(function () { console.log('Server closed!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
})(Max);
Chatroom2-0.php
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width:95%;
rows:50;
height:80%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript">
var str = "";
function enter(e){
if (e.keyCode == 13 && document.getElementById("Input").value) {
//alert("Enter!!!!");
sendInput();
document.getElementById("Input").value = "";
}
};
function updateBoard() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
}
var textarea = document.getElementById('Output');
textarea.scrollTop = textarea.scrollHeight;
};
xmlhttp.open("POST","Server.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
};
function sendInput() {
username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
if (msg) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Server.php",true);
//xmlhttp.open("POST","test.txt",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
//alert(xmlhttp.responseText);
}
};
</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
if (isset($_POST["Username"]))
echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
else {
header("Location: /login/index.html");
die();
}
?>
<input type="text" id="Input" onkeypress="enter(event)" value="" >
</form>
</body>
</html>
Users should be able to access the Chatroom2-0.php after login. The login functionality is also ok. But when I entered the Chatroom2-0.php, I got a String, next to my textbox.
'; else { header("Location: /login/index.html"); die(); } ?>
I noticed that the string is part of my php code in the file. I don't know what's happening. I think this might have something to do with the response.write() or the data.toString() function. Maybe the function changed something in my coding? How could I solve this problem.
Anyway, I appreciate for any help given.
The problem is that you are trying to run php code on a nodejs server. There is no solution to this, as node is not a php interpreter, so it sees everything as html text; thus your php code appearing on the page. You need to create an entirely different html for the node project.
When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped. Is there a way that I should be passing a reference?
the console output is as follows
[12:29:06.839] GET getterms.php?query=DFA [HTTP/1.1 200 OK 99ms]
[12:29:06.888] SyntaxError: JSON.parse: unexpected character # search.php:21
[12:33:24.316] console.log(req.responsetext)
[12:33:24.318] ReferenceError: req is not defined
Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse(req.responseText);
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Scope problem! Remove var in front of req to make it global and it should work
So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON