How to communicate between Python3 and JavaScript via sockets - javascript

I just set up a small TCP-socket server in python3, which waits for a connection, sends a small encoded text and waits for data from the client.
Python-Code:
import socket
sock = socket.socket()
sock.bind(("0.0.0.0", 20000))
sock.listen(5)
while True:
Client, address = sock.accept()
Client.send("ping".encode())
print(Client.recv(1024).decode()) # Here I want to receive data from the client
Client.close()
At the end, there should be a browser interface which can communicate with the python backend with JQuery or just something that receive and send (With data!) sockets.
Thank you :D
EDIT:
Forgot to say that I can receive the text in a browser, I just need to know how to send data back.

if you need to connect to a NodeJS javascript environment then you should take a look at this native package
https://nodejs.org/api/net.html#class-netsocket
if you need to connect to a browser javascript environment then you should take a look at WebSockets
Python: https://websockets.readthedocs.io/en/stable/#:~:text=websockets%20is%20a%20library%20for,an%20elegant%20coroutine%2Dbased%20API.
Javascript https://developer.mozilla.org/es/docs/Web/API/WebSockets_API

Related

Why is the c# websocket client not receiving data?

There is a very good utility called ttyd, which allows you to run a console application on your computer and display this console in the browser.
After startup, the utility starts an http web server on the specified port and when accessing localhost, a website with a web application that connects using web sockets to localhost:<port>/ws, and already with the help of them there is communication between the web application and the ttyd agent running on the computer.
I want to implement a client for ttyd in c#. I studied with the help of chrome tools what data the web application sends before receiving the data output to the console. This is just a string: {"authToken":"","columns":211,"rows":46} and tried to repeat the same actions in the c# client. But for some reason, no data from ttyd is returned to me.
Comparing the data output by ttyd to its console in the OS itself, it can be seen that it does not even create a process when accessing from my client.
Here is the code I use with the Websocket.Client package
var exitEvent = new ManualResetEvent(false);
var url = new Uri("ws://localhost:7681/ws");
using (var client = new WebsocketClient(url))
{
client.ReconnectTimeout = TimeSpan.FromSeconds(30);
client.ReconnectionHappened.Subscribe(info =>
Console.WriteLine($"Reconnection happened, type: {info.Type}"));
client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
client.Start();
Task.Run(() => client.Send("{\"AuthToken\":\"\",\"columns\":211,\"rows\":46}"));
exitEvent.WaitOne();
}
I have absolutely no idea how to get ttyd to send data to my client. Do you have any idea what action the browser is doing I'm missing in my c# client?
I tried different libraries for web sockets in c#, and also used postman with copying all the headers that the original web application sends to the ttyd agent, but this does not change anything. That is, ttyd, something is fundamentally interfering, as if my web client is not doing something that the browser is doing.

The PHP file_get_contents command does not work when read data from the Node.js server

I try to send messages from PHP server to Node.js server. The purpose of the Node.js server is to convey the message forward using the Socket.io and Express.
$NodePage = file_get_contents($NodeServer. "/index.html?&message=". $message);
The server always returns empty string and do not send a message. Same URL in browser working Ok and a message is sent correctly. I also try redirect command.
header("Location: http://xxxxxxx.fi/index.html?message=". $message);
Also returns empty string. Working Ok in web browser. I make PHP calls from C# client.
HtmlWeb web = new HtmlWeb();
string tempURL = _url + _htmlMessageStr +
"?message=" + msg.fullMessage) ;
HtmlDocument doc = web.Load(tempURL);
HtmlNodeCollection tags =
doc.DocumentNode.SelectNodes(_nodeText);
_retVal = parse(tags[0].InnerHtml);
Any other data is ok from PHP, except node data (empty string). I tried to retrieve data from other Node.js servers and it restore the data correctly. Something is wrong with my Node.js server but what? Server is hosted by hosting company. The server does not run anything other than Node.js.
This needs to be enabled in the php.ini. The option you are searching for is "allow_url_fopen" and set it to true.
http://php.net/manual/en/filesystem.configuration.php
I found the problem. You can not use the file_get_contents command to connect Socket.io to the Node.js server. You need to connect to the socket.io.
This article explains how to do it.
enter link description here

Display Kafka messages on web page

I have a Java Spring Application with a Tomcat server that listen on kafka topic. I want to display all messages in a real-time mode on the web page. Therefore, when a kafka messages is arrived in the backend I want to see it on my web page. I don't know a good approach to push kafka message directly to the front-end and display it on web page. Is someone could help my with a solution and some examples that could help? Thanks!
I have implemented a system like this in Java for my last employer, albeit not with Spring/Tomcat. It was consuming messages from Kafka and serving them on a web socket to be displayed in the browser. The approach I followed was to use akka-stream-kafka and akka-http for web-socket support. The benefit of that is both are based on akka-streams which makes it an easy fit for streaming data.
While you can embed akka-http in your spring app running inside tomcat, it may not feel the most natural choice any more as spring framework already has its own support for both kafka and websockets. However, if you're not familiar with either, then jumping on the akka approach may be easiest and the core logic goes along these lines (I can't share the code from work so have just put this together from the examples in the docs, not tested):
public Route createRoute(ActorSystem system) {
return path("ws", () -> {
ConsumerSettings<byte[], String> consumerSettings = ConsumerSettings.create(system, new ByteArrayDeserializer(), new StringDeserializer())
.withBootstrapServers("localhost:9092")
.withGroupId(UUID.randomUUID().toString()) //this is so that each client gets all messages. To be able to resume from where a client left off in case of disconnects, you can generate in on the client side and pass in the request
.withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
return handleWebSocketMessages(
Flow.fromSinkAndSourceCoupled(
Sink.ignore(),
Consumer.committableSource(consumerSettings, Subscriptions.topics("topic1"))
.map(msg -> TextMessage.create(msg.record().value()))
)
);
}
}
To expose this route you can follow the minimalistic example, the only difference being the route you define needs the ActorSystem:
final Http http = Http.get(system);
final ActorMaterializer materializer = ActorMaterializer.create(system);
final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = createRoute(system).flow(system, materializer);
final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow,
ConnectHttp.toHost("localhost", 8080), materializer);
Once you have your messages published to the websocket, the front end will code will of course depend on your UI framework of choice, the simplest code to consume ws messages from javascript is:
this.connection = new WebSocket('ws://url-to-your-ws-endpoint');
this.connection.onmessage = evt => {
// display the message
To easily display the message in the UI, you want the format to be something convenient, like JSON. If your Kafka messages are not JSON already, that's where the Deserializers in the first snippet come in, you can convert it to a convenient JSON string in the Deserializer or do it later on in the .map() called on the Source object.
Alternatively, if polling is an option you can also consider using the off-the-shelf Kafka Rest Proxy, then you only need to build the front-end.

instant messaging system using JavaScript

I have a school project where i need to create an instant webbased messageing system.
Ive looked into PHP sockets to complete this task PHP socket manual
From these im starting to see a pattern. As you well know PHP can only run once (from top to bottom) and from these examples i can see that a while loop is what makes the socket listen for new connections. (meaning the php script never stops) these examples the echo the output of the socket.
as far as i can see this is great if you just want a plain site.
However this is not the case. I want to build this application using JavaScript to "ask" the socket if there is any new messages and if there is then render the messages accordingly.
Since im very new to PHP sockets im not sure if this should be done purely by PHP or if it is possible to use JavaScript to listen to the socket (via Ajax) and then print the output as a JSON?
I recommend you to use a third party library (well, an recommend you again this library: cboden/ratchet). Read its tutorials and you will have a cleaner look at how to communicate between browsers ans servers using WebSocket protocol.
The server is absolutely able to be implemented with pure PHP!
In general for push based notifications the protocol you will want (which only works with newer browsers) is WebSockets.
There are a variety of libraries and services which can do this for you:
Pusher, is an online service which can integrate with a variety of languages to give you real time functionality. https://pusher.com/
In JavaScript only, and if you have node you should look at socket.io : http://socket.io/
In .NET land, there is SignalR which is fantastic http://signalr.net/
Not only is it possible to do with PHP but it's also trivial with Thruway. Thruway is a WAMPv2 PHP client/router that uses Ratchet for the Websocket transport. WAMP gives you Sub/Pub and RPC over WebSockets.
You would need to create a simple php router and start it from the command line. Something like this:
<?php
require 'vendor\autoload.php';
use Thruway\Peer\Router;
use Thruway\Transport\RatchetTransportProvider;
$router = new Router();
$transportProvider = new RatchetTransportProvider("127.0.0.1", 9090);
$router->addTransportProvider($transportProvider);
Then on the client, use AutobahnJS or if you're using angular, you can use angular-wamp.
If you still have questions, I'll work up a simple chat example.
I actually used a PHP based websocket and adapted it. I can work both ways if you want. You can store the messages sent to the websocket in an Array or even let them be saved into a database. The client can ask for new messages:
look at this code:
function createConnectionToWebSocket(connection)
{
var host = "ws://[ip of server]:9000/echobot"; // SET THIS TO YOUR SERVER --> 9000 is the port used by websockets.
try {
socket = new WebSocket(host);
console.log('WebSocket - status '+socket.readyState);
socket.onopen = function(msg) {
console.log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
messageHandlerSocket(msg.data);
};
socket.onclose = function(msg) {
console.log("Disconnected - status "+this.readyState);
if (msg && !msg.wasClean && msg.code == 1006)
{
}
};
socket.onerror = function(msg) {
};
}
catch(ex){
console.log(ex);
}
}
function messageHandlerSocket(msg)
{
//all messages will be send in JSON
var msg = JSON.parse(msg)
//received JSON and check the type. Type is message
switch (msg.type)
{
case "messages" :
//code when the webserver sends back the messages.
break;
}
}
socket.send(JSON.stringify({"type" : "retrievemessages", "user" : user.id}));
Socket.send allows you to send data to the PHP server. I send JSON and parse this on the server. Based on the type argument I let the PHP server send data back to the corresponding user.
I extend this webserver I found on Github.
Run the webserver via a bat-file.
#ECHO OFF
ECHO STARTING WEBSERVER
ECHO USING [dir to php dir]\php\php.exe
#ECHO OFF
START "WEBSOCKET" /wait /B "[dir to php dir]\php\v5.6\php.exe" -f [path to your websocket.php]

Javascript and MySQL

I want to build an entire web app using only Javascript and MYSQL . How can I go about this if it's possible.
Try something like Jaxer, which will allow you to execute JavaScript on the Web Server and query databases.
Here are some syntax examples and usages:
Database, file, and socket access from JavaScript
alt text http://jaxer.org/images/Picture+4_0.png
Easily create RESTful JSON data services
alt text http://jaxer.org/images/Picture+6.png
Directly call server-side functions from the browser
alt text http://jaxer.org/images/Picture+2_0.png
You can do it with Jaxer. There are some screencasts that'll get you started. Also check out project Phobos. Jaxer integrates nicely in Aptana studio, Phobos in Netbeans.
If you can run javascript on the server, you can build a web-application with it (without the need for any other language like PHP etc.). Search the web for 'connection string mysql' to find out how to connect to your mySQL database and use ADO/ODBC. You'll need the MySQL ODBC-connector on the MySQL server.
Here's an example database connection (where MySQL server resides on the same server as the web server):
function connectDB()
{
var connectStr = "DRIVER={MySQL ODBC 3.51 Driver}; " +
"SERVER=localhost; " +
"PORT=[MySQL server port];" +
"DATABASE=[your database]; " +
"UID=[username];PWD=[password];" +
"OPTION=3",
conection = Server.CreateObject("ADODB.Connection");
//ERRID=>lib::connectDB::open
try {connection.Open(connectStr) }
catch(e) {errAlert(e,'rs::connectDB','connection failed',1) }
return connection;
}
(Where errAlert is a custom function to return the error)
You could write your application entirely in client side javascript with AJAX / REST calls to your database server - using something like CloudKit on your server (or CouchDB, which features a native JSON HTTP interface). On the client side, Dojo or YUI abstract out a great deal of the IO handling…
It's quite possible to write a web application using only javascript. One the key benefits of that is that since all code runs locally, you can make an application which doesn't require online connectivity.
The main detractor though, is that you can't hook it up to a database. But there are alternative data storage hacks you can use.
One example of such a javascript application is TiddlyWiki which is a personal wiki, contained in a single html file. The javascript application rewrites that html file, so you can carry it with you on a USB-drive or something.
You could look at triplify which should expose your database as json and rdf. I haven't actually used this but I would imagine that would let you bypass writing any server side js and talk to the database directly in a language javascript understands, using an ajax request and json.
You can build client-side applications in javascript, with an embedded database. HTML 5 has support for databases, and a couple of browsers have already implemented this part of the spec (safari, firefox with the gears plugin).
But this is only for clientside usage. You wont be able to share the database with other users. Also you can select which database you want to use. I think gears uses sqlite.
You will not be able to use Javascript and MYSQL without using something such as PHP on the server side to bridge the gap between the database and the Javascript on the client side.
Edit: I may be wrong, however I have no idea how you would run Javascript on the server side.

Categories