I want to implement a small multiplayer client/server game. It's my concurrent program project. I wrote the application's basic logic in Java and it's working. I want to make it web based. I am not sure how to do it. Here is a small part that I want to implement:
<%#page import="javacode.Client"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
Client client = new Client();
boolean b = client.connect();
%>
<%= b%>
<script type="text/javascript"></script>
<script type="text/javascript">
function sendToServer(){
var line = document.getElementById("input").value;
//send line to server using client.send()
client.send(line);
//get response from server to client using client.get()
line = client.get();
document.getElementById("input").value=line;
}
</script>
<html>
<head></head>
<body>
<br>
<input type="text" name="input" id="input"/>
<input type="button" value="send" onclick="sendToServer()"/>
<input type="text" name="output" id="output" />
</body>
</html>
I am starting a chat echo server then opening this JSP page. It's connecting to the server by creating a client object. But I want to use the same client object for further communication with the server. Whenever I click the send button it has to get an input field's value and send it to the server, then get the response from the server with the client.get() method and set the value to output field. As a Java program Client.java is working fine, but I am not sure how to do it web based.
PS: I don't want to use an applet.
Related
There are two files: 1)app.js and 2) browser.html. app.js just stores a value in a node-js local storage and browser.html should alerts that. But browser.html alerts "null".
My JavaScript code:
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
var a="salam";
global.a=a;
localStorage.setItem('a',a);
My html code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
</head>
<body>
<input value="Smart contract data" max="25" id="12"></input>
<script src='js/app.js'> </script>
<script>
alert(localStorage.getItem('a'));
</script>
</body>
</html>
What is the problem and its solution? Is there any way to communicate between node-js storage and a html file? Please guide a beginner man.
The issue here is that node-localstorage is entirely backend, and htlm5 localStorage is entirely client side. You will not be able to pull backend values set with node-localstorage on the client end.
In order to pass values from node to the client you will need a template engine. Express provides a pretty complete list of those engines here:
https://expressjs.com/en/resources/template-engines.html
I have a website with a form allowing users to upload files ( pdf or docx ). I'm trying to execute some python code on the file loaded and return and print the text of the file on the HTML page.
After some research, I understood that :
we call the python script thanks to the html form. This call execute the python script which receives the data throught the post method
The python script does his job and return html code with the result.
For the html part :
<html>
<head>
<title></title>
</head>
<body>
<h1>Upload File</h1>
<form action="example.py" method="POST" enctype="multipart/form-data">
File: <input name="file" type="file">
<input name="submit" type="submit">
</form>
</body>
</html>
For the python part :
def convert_doc_to_text(filename):
text = textract.process(filename) # extract text from file
return text.decode('utf-8')
With which technology would I be able to host and execute the python script ?
How could I transfer the file uploaded between the website server and the python script server ?
Thanks in advance.
I would like to post data to my PHP page and then have it update the HTML page. I followed this example of using server-sent events to push updates to a webpage.
Here is what I have right now:
output.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="serverData"></div>
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$val = 0;
if (isset($_POST['msg'])){
$val = $_POST['msg'];
}
echo "data: $val\n\n";
ob_flush();
?>
form.html:
<html>
<body>
<form action="send_sse.php" method="post">
Message: <input type="text" name="msg"><br>
<input type="submit">
</form>
</body>
</html>
The problem is that when the form posts the value, it does not update the output.html. It does output "0" and will update whenever I manually change the value of $val and save the file. However, I want the value of $val to be determined outside of the PHP file. What am I doing wrong?
The issue you are having here is that you have missed how SSE conceptually work. Your output.html page is making a GET request to your web server and executing the script send_sse.php and opening up a connection and HOLDING that connection open and waiting for updates.
When you are posting from form.html you are sending a POST request to your web server and executing the script send_sse.php on a completely different thread.
As you have not implemented any shared persistence between these two threads it will make no difference.
So to do what you want to do you will need to have code in send_sse.php that has some form of global persistence (e.g. database) and can detect new data and then flush that down to the browser.
I am not a PHP expert, but I have written an example in Node JS that uses REDIS pub/sub to provide said persistence.
I hope that helps.
To upload a local file to Google Drive, I have an HTML <form></form> (see code below) that displays in a modal overtop a Google Sheet the user has open. The HTML form has <input type="file" name="..."> in it, and when I click to send the form object, I successfully upload the file if this Google Apps Script is "bound" to a specific Sheets file (and was written using the Tools > Script Editor... menu).
If I save the script as a standalone script and then test it (installed and enabled) on a Sheets file of my choosing, then the <form>'s onclick action and the attempt to call google.script.run.aServerFunction(...) causes a "NetworkError: Connection failure due to HTTP 403". To clarify this is what I mean by creating a standalone script and testing it on a Sheets file: https://developers.google.com/apps-script/add-ons/#understand_the_development_cycle. In earlier code iterations I alternatively got a authorization scriptError of some kind. Same error when script is published privately for testers to use on a Sheet. Unfortunately, I think I need this as a standalone script that is later publishable as an add-on- not a side script bound to a single Sheet using the Tools > Script Editor... menu.
My first post to Stack Overflow- please forgive any jargon or typography mistakes, and thank you!
HTML adapted from tutorials:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function failed(event) {
$("div.response").text(event);
//google.script.run.selectStuff();
//google.script.host.close();
}
</script>
</head>
<body>
<form id="myForm">
<label>Your Name</label>
<input type="text" name="myName">
<label>Pick a file</label>
<input type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="google.script.run.withFailureHandler(failed)
.uploadFiles(this.parentNode);
return false;">
</form>
<div class="response"></div>
</body>
</html>
In the code.gs:
function uploadFiles(formObject) {
/*var sheet1 = SpreadsheetApp.getActiveSheet();
sheet1.setActiveRange(sheet1.getRange(2, 2, 4, 4));
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
driveFile.addEditor("...");
SpreadsheetApp.getActive().toast(driveFile.getUrl());
sheet1.getRange(1,1,1,1).setValue(driveFile.getUrl());
return driveFile.getUrl();*/
return "it worked";
}
I believe the reason you are getting the HTTP 403 error is because form DOM elements are illegal arguments in google.script.run.myfunction(...) in sheet addons. Even though they are mentioned here as legal parameters here, I think add-on have the added restriction of not being able to pass any kind of DOM elements.
The solution I came up with is to convert the uploaded file to base64 encode string using Filereader.readAsDataUrl() function in native javascript and passing the string to google script and converting it back to a file to be uploaded into google drive.
The base64 encode string starts like this:
data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTG....
GAS
function uploadFiles(formObject) {
// extract contentType from the encoded string
var contentType = formObject.split(",")[0].split(";")[0].split(":")[1]
// New Blob(data,contentType,name)
// Use base64decode to get file data
var blob = Utilities.newBlob(Utilities.base64Decode(formObject.split(",")[1]), contentType, "trial")
var driveFile = DriveApp.getFolderById("your Folder ID here").createFile(blob);
//return contentType, can be anything you like
return blob.getContentType()
}
HTML script
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
<form id="myForm">
<label>Your Name</label>
<input type="text" name="myName">
<label>Pick a file</label>
<input type="file" id = "filemy" name="myFile">
<input type="button" value="Upload File"
onclick="upload(this.parentNode)">
</form>
<div class="response"></div>
</body>
<script>
function failed(event) {
$("div.response").text(event);
//google.script.run.selectStuff();
//google.script.host.close();
}
function upload(frmData){
var file = document.getElementById("filemy").files[0]
var reader = new FileReader()
//reader.onload is triggered when readAsDataURL is has finished encoding
//This will take a bit of time, so be patient
reader.onload = function(event) {
// The file's text will be printed here
console.log("File being Uploaded")
//console.log(event.target.result)
google.script.run.withFailureHandler(failed).withSuccessHandler(failed)
.uploadFiles(event.target.result);
};
reader.readAsDataURL(file);
console.log(reader.result)
}
</script>
</html>
Final notes: I have not extensively tested the code, I have got it to work with a pdf file and an image/png file with a Maximun size of 2.6MB. So please try these 2 file types out before going on to further types of file!
Also, files do take a while to upload so be patient(~5-10sec). Especially since there is no progress bar to show the upload progress, it feels like nothing is happening.
Hope that helps!
I'm trying to take input from a form and save it into a text file that is in the same folder as the html file. This is what I have so far:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reservation</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script>
function writeToFile(item, name, time)
{
alert("Hello " + item);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("E:/labChart/etc/reserve.text", 8);
fh.WriteLine(item);
fh.Close();
}
function readFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("reserve.text", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
</script>
</head>
<body>
Reservation
<br>
<form>
Item:
<br>
<input type="text" name="item" id="item">
<br>
Name:
<br>
<input type="text" name="name" id="name">
<br>
Time:
<br>
<input type="date" name="time" id="time">
<br>
<br>
<input type="submit" value="Submit" onclick="writeToFile(document.getElementById('item').value, document.getElementById('name').value, document.getElementById('time').value)">
</form>
<script src="js/scripts.js"></script>
</body>
</html>
This does take the info from "item" and pass it to the function writeToFile() because the test alert does work. But whenever I check the file reserve.text nothing is written there. I'm very new to javascript and most of this is an amalgamation of code I saw other people using online for similar effects. Does anyone know why it is not working? Am I writing the path incorrectly? Am I not writing the script correctly?
The problem with this is simple: Lets say a developper created javascript code to go through all your filesystem and populate it with dummy files, ruining your hard drive in the process? That is why javascript won't allow you to do this kind of operation. When we want to save information, usually, its done using server-side code and not the client's computer (unless of course we are talking about things like cookies).
The point of my answer is to let you rethink who does the saving and to where. It should be up to the server to save and retain any information for a user, and so you would not write this kind of javascript code... It is best to save data somewhere your client cannot control or edit, like on the server for instance.
I could suggest some easy PHP code, and instead of storing inside a text file, try a database... PHP is a server-side language which will let you save things to files on your server computer, however your server must be able to run PHP, most computers don't come built in with the PHP language and so you will also need a webserver with php built-in..
In my opinion your entire approach is bad; you need to learn PHP and mySQL to store and load persistent data.
- Edit: accessing the file system from JavaScript is a huge security risk and therefore not allowed in general. Unless your goal is specifically to write files from JS, there are better alternatives.
Anyway, this code will only work on Internet Explorer, and only with the security settings way down. You shouldn't pursue this though.
If your end goal is to write a web app that stores and displays reservations, get XAMPP and find a beginner PHP + database tutorial.