websocket protocol access from remote computer - websocket

I have designed a chat application based on websocket protocol.
i have installed a xampp server in computer A .I start the server in computer A and then I am trying to access client.php page (url is ipadresssofA/project/client.php) from computer B using the ip address of computer A. But it is displaying socket error.
And when i try same url on computer A (url is ipadresssofA/project/client.php). client get connects.BOTH COMPUTERS ARE CONNECTED WITH SAME WIFI.
Here is my client code.please tell me what is wrong
<html>
<head>
<style>
#chatlog {width:440px; height:200px; border:1px solid;overflow:auto;}
#userslog {width:440px; height:200px; border:1px solid;overflow:auto;}
#msg {width:330px; height:100px;}
</style>
<script>
function initialize(){
var host = "ws://localhost:12345/project/server3z.php";
try{
socket = new WebSocket(host);
chatlog('WebSocket - status '+socket.readyState);
socket.onopen = function(event){chatlog("WebSocket status "+this.readyState); };
socket.onmessage = function(event){ chatlog(event.data); };
socket.onclose = function(){ chatlog("WebSocket status "+this.readyState); };
socket.onerror = function(event){chatlog("Error :"+event.data); };
}
catch(err){ chatlog(err); }
}
function send()
{
var chat;
chat= document.getElementById("msg").value;
if(!chat){ alert("Message can not be empty"); return; }
try{ socket.send(chat); chatlog('Sent: '+chat); } catch(err){ log(err); }
document.getElementById("msg").value = "";
}
function quit(){
chatlog("closed!");
socket.close();
chatlog("WebSocket status "+socket.readyState);
}
function chatlog(msg)
{
var match=msg.match(/10101010101010/g);
if(match)
{
var msg=msg.split("10101010101010");
document.getElementById("userslog").innerHTML+="<br>"+msg[0];
}
else
{
document.getElementById("chatlog").innerHTML+="<br>"+msg;
}
}
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>
</head>
<body onload="initialize()">
<center>
<div id="chatlog"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">Send</button>
<button onclick="quit()">Stop</button>
<div id="userslog"></div>
</center>
</body>
</html>
Also in my server code something is written in comments which i want to show you :
// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('localhost', 12345);

Initialize var host as follows:
var host = "ws://localhost:12345";
Everything else looks ok.

Related

Can I connect to Memgraph using websocket?

Does Memgrpah support connections over WebSocket? I couldn't find the minimal required code to do that.
All that you need is a client that uses WebSocket to connect to Memgraph, and Memgraph will automatically recognize the nature of the connection. The port you will be connected to remains the same.
You should use Memgraph's address and the port number defined by the configuration flag --bolt-port to connect to Memgraph (7687 is the default port).
To connect to memgraph via WebSocket you can use the JavaScript client. Minimal code to connect would be:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Javascript Browser Example | Memgraph</title>
<script src="https://cdn.jsdelivr.net/npm/neo4j-driver"></script>
</head>
<body>
<p>Check console for Cypher query outputs...</p>
<script>
const driver = neo4j.driver(
"bolt://localhost:7687",
neo4j.auth.basic("", "")
);
(async function main() {
const session = driver.session();
try {
await session.run("MATCH (n) DETACH DELETE n;");
console.log("Database cleared.");
await session.run("CREATE (alice:Person {name: 'Alice', age: 22});");
console.log("Record created.");
const result = await session.run("MATCH (n) RETURN n;");
console.log("Record matched.");
const alice = result.records[0].get("n");
const label = alice.labels[0];
const name = alice.properties["name"];
const age = alice.properties["age"];
if (label != "Person" || name != "Alice" || age != 22) {
console.error("Data doesn't match.");
}
console.log("Label: " + label);
console.log("Name: " + name);
console.log("Age: " + age);
} catch (error) {
console.error(error);
} finally {
session.close();
}
driver.close();
})();
</script>
</body>
</html>
You can find more info at Memgraph documentation site.

Browser does not render appended child node

I'm experimenting with web service to transmit new elements to document DOM.
So I'm preparing a XML on server side with necessary informations to do that job. My server side XML is as followed:
<Root>
<Command>Add
<Data><button id="PB" style="width:600px; height:100px;"/></Data>
</Command>
</Root>
This XML will be caught by following page.
You will see XML has a command id "Add", which should add the nodes below data to the page.
When code is running, the button will be created and shown properly in document DOM (see code function onMessage), but it will not be rendered.
The browser debugger tells me, the width and height of the button seems to be Null. When I edit the attributes in browser debugger, the button will be rendered after change. I get this behaviour on Chrome and IE.
I need a hint, what has to be changed to let it run.
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:8002/chat";
var output;
var websocket;
"use strict";
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var parser, xmlDoc, NodeCommand, but;
parser = new DOMParser();
xmlDoc = parser.parseFromString(evt.data, "text/xml");
NodeCommand = xmlDoc.getElementsByTagName("Command");
switch (NodeCommand[0].textContent) {
case "Add":
output.appendChild(NodeCommand[0].childNodes[1].childNodes[0]);
break;
}
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Solved!
This can't be done in this (intuitive) way. Elements have to be created over document.

How to integrate svg-edit to ASP.NET MVC application

I am about to integrate svg-edit to an ASP.NET MVC project.
Is there anyone who has a recommendation or tutorial on how to begin with?
Thank you.
I am answering my own question.
After a research, I recommend deploying the whole SVG-EDIT lib into mvc architecture, then modify the embed api as following:
This is my Partial View and JS file that call the embed api and put it into the iframe within the partial view:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
// Make sure to add the embedapi into the html file, becuase the intialization function runs actually in that file, all this call does is basically to take the iframe from html and inialize the api within that tag.
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here I have a save and load functions ready for the module: There is so much work to do in order to perfect the algorithm, but since this was just a test project to figure out the possibility of integrating the module into the environment I put enough effort to understand that share the knowledge with the community:
Here is my cshtml file:
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here is the js file:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
document.write("<script src='~/Scripts/jquery-1.10.2.js'></script>");
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
$(document).ready(function () {
// jquery selectro
$("#save1").click(function () {
$("#DivData").append("<b>Appended text</b>");
});
});
$(document).ready(function(){
$("#CloseSVG").click(function () {
$("#svg").hide();
});
});
function HandleSvgData(data,error) {
if (error) {
alert('Error:' + error);
} else {
$('#DivData').append(data);
alert(data);
}
}
function handleSvgData(data, error) {
alert("handling Data");
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
}
}
function save1() {
alert("saving");
// svgCanvas.getSvgString()(handleSvgData);
$("#svgedit").append($('This is the test classed appended after DivDat'));
}
function AddNewElemnt()
{
var newElement = document.createElement("Test");
var newNode = document.createTextNode("This is my new node!");
newElement.appendChild(newNode);
var referenceElement = document.getElementById("mainBody");
var tagInsert = document.getElementById("TestId");
referenceElement.insertBefore(newElement, tagInsert);
// alert("added");
}
function Postt(data) {
}
function Post(data) {
var mainBody = document.getElementById("mainBody");
var SvgDataId = prompt("give me primary id");
var SvgUser = prompt("give me UserName");
var form = document.createElement("form");
form.setAttribute("id", "PostData");
form.setAttribute("action", "/SvgDatas/Create");
form.setAttribute("method", "post");
mainBody.appendChild(form);
var PostData = document.getElementById("PostData");
var InputSvgDataId = document.createElement("input");
InputSvgDataId.setAttribute("name", "SvgDataId");
InputSvgDataId.setAttribute("value", SvgDataId);
PostData.appendChild(InputSvgDataId);
var InputSvgUser = document.createElement("input");
InputSvgUser.setAttribute("name", "SvgUser");
InputSvgUser.setAttribute("value", SvgUser);
PostData.appendChild(InputSvgUser);
var InputData = document.createElement("input");
InputData.setAttribute("name", "Data");
InputData.setAttribute("value", data);
PostData.appendChild(InputData);
form.submit();
}
function save() {
var doc, mainButton,
frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
// Hide main button, as we will be controlling new, load, save, etc. from the host document
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
mainButton.style.display = 'none';
// get data
svgCanvas.getSvgString()(function handleSvgData(data, error) {
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
Post(data);
}
});
}
/*
function BuidUrl(SVGUser) {
var uri = prompt("Give me url where the serach function lives, if empty then I will use Razor syntax to call within MVC architescture");
if (uri)
return uri;
else {
var urlHelper = ('http://localhost:53546/SvgDatas/Search?id='+SVGUser);
return urlHelper;
}
}
*/
function returnedData_IntializeEditor(data, status) {
if ((data != null) && (status == "success")) {
var frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
tool_Bottum = doc.getElementById("#tool_button");
mainButton.style.display = 'none';
// Open Data into the frame
// var svgexample = '<svg width="640" height="480" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><g><title>Layer 1<\/title><rect stroke-width="5" stroke="#000000" fill="#FF0000" id="svg_1" height="35" width="51" y="35" x="32"/><ellipse ry="15" rx="24" stroke-width="5" stroke="#000000" fill="#0000ff" id="svg_2" cy="60" cx="66"/><\/g><\/svg>';
svgCanvas.setSvgString(data.Data);
} else {
$("#svg").append("<li>There is not such a data available in the database!</li>");
}
}
function LoadExample() {
var SVGUser = prompt("Enter the SVG ID");
$.getJSON("http://localhost:53546/SvgDatas/Search?id=" + SVGUser, returnedData_IntializeEditor );
}
This is the model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace IntegrationOfSVG.Models
{
public class SvgData
{
public string SvgDataId { get; set; }
public string SvgUser { get; set; }
public string Data { get; set; }
}
}
Thank you SVG-EDIT community for the great tool.
Next I am planning to add a view mode to this module that opens the data from a sequal server and if the mode is admin, lets the user to edit the existing data. I will keep this posted updated.
1- One way is to remove the tools from the client side, but it has a certain limitation that is the fact that css does not adjust a
function RemoveTools() {
var frame = document.getElementsByClassName("iFrameHtmlTag")[0];
doc = frame.contentWindow.document;
if (doc != null) {
var Tools = [
'tools_top', 'tools_left', 'tools_bottom', 'sidepanels', 'main_icon', 'rulers', 'sidepanels', 'canvashadow'];
for (i=0; i<Tools.length;i++)
{
doc.getElementById(Tools[i]).style.display = "none";
}
} else
alert("Doc was null");
};
$(document).ready(function () {
$("#hide").click(function () {
RemoveTools();
});
});
It is an effective way, but there should be a better method to view the object with few parameters also to readjust the size of the window. I will continue with that topic too.

How to use WebSockets broadcast for play framework 1.2.7

My code can work.But only refresh a page of one window.
If I open window1 and window2 , both open websocket connect.
I keyin word "test123" in window1, click sendbutton.
Only refresh window1.
How to refresh window1 and window2 ?
Client
<script>
window.onload = function() {
document.getElementById('sendbutton').addEventListener('click', sendMessage,false);
document.getElementById('connectbutton').addEventListener('click', connect, false);
}
function writeStatus(message) {
var html = document.createElement("div");
html.setAttribute('class', 'message');
html.innerHTML = message;
document.getElementById("status").appendChild(html);
}
function connect() {
ws = new WebSocket("ws://localhost:9000/ws?name=test");
ws.onopen = function(evt) {
writeStatus("connected");
}
ws.onmessage = function(evt) {
writeStatus("response: " + evt.data);
}
}
function sendMessage() {
ws.send(document.getElementById('messagefield').value);
}
</script>
</head>
<body>
<button id="connectbutton">Connect</button>
<input type="text" id="messagefield"/>
<button id="sendbutton">Send</button>
<div id="status"></div>
</body>
Play Framework WebSocketController
public class WebSocket extends WebSocketController {
public static void test(String name) {
while(inbound.isOpen()) {
WebSocketEvent evt = await(inbound.nextEvent());
if(evt instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame)evt;
System.out.println("received: " + frame.getTextData());
if(!frame.isBinary()) {
if(frame.getTextData().equals("quit")) {
outbound.send("Bye!");
disconnect();
} else {
outbound.send("Echo: %s", frame.getTextData());
}
}
}
}
}
}
You have the basic of making work a single socket. However, each socket you are creating uses your socket events. Since each of the sockets would equal a thread, you need to send the event for each socket you can have. This is why when a new socket is open you need to map it in an array of sockets.
This thread can help you out.
Websocket send data all client in playframework 2
And refer to this exemple of play with framework.
https://github.com/playframework/playframework/blob/master/samples/java/websocket-chat/app/models/ChatRoom.java#L89

AJAX: I am unable to fetch the data from server side

I need to get output from my server side code but i am able to fetch it.
I have used script manager and script manager proxy control in master page.
How can i get the string that is being returned from the cs file
Here is my Default.aspx code
<asp:UpdateProgress runat="server">
<ProgressTemplate >
Loading..........
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label ID="lbl" Text="Enter Your Name" runat="server"></asp:Label>
<input type="text" id="txt" /><br />
<input type="button" id="btn" value="Submit" onclick="makeGetRequest()" />
<div id="description">Hello</div>
</ContentTemplate>
</asp:UpdatePanel>
<script language="Javascript" type="text/javascript" >
function createRequestObject() {
var tmpXmlHttpObject;
if (window.XMLHttpRequest) {
// Mozilla, Safari would use this method ...
tmpXmlHttpObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE would use this method ...
tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
return tmpXmlHttpObject;
}
var http = createRequestObject();
function makeGetRequest() {
http.open('post', 'Default.aspx/greet',true);
//assign a handler for the response
http.onreadystatechange = processResponse;
//actually send the request to the server
http.send(null);
}
function processResponse() {
if (http.readyState == 4) {
var response = http.responseText.toString();
alert("Inside here before");
document.getElementById('description').innerHTML = response;
alert("Inside here after");
}
}
</script>
// my default.aspx.cs file
[WebMethod(EnableSession=false)]
public static string greet()
{
return "hello";
}
I am getting all contents of the page copied instead of getting response from it
the line var http = createRequestObject(); have to be the first line inside function makeGetRequest() function. anyway, i am posting a working code.
<script language="Javascript" type="text/javascript" >
function makeGetRequest() {
var http;
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var response = http.responseText.toString();
alert("Inside here before");
document.getElementById('description').innerHTML = response;
alert("Inside here after");
}
}
http.open('post', 'Default.aspx/greet', true);
http.send(null);
}
</script>

Resources