Sorry for the noob questions, i'm new on it.
I have a python server, and client and it's working.
There are :
import socket
def Main():
host = "127.0.0.1"
port = 5000
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
print ("from connected user: " + str(data))
data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())
conn.close()
if __name__ == '__main__':
Main()
and client
import socket
def Main():
host = '127.0.0.1'
port = 5000
mySocket = socket.socket()
mySocket.connect((host,port))
message = input(" -> ")
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print ('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
Main(
But when i want to make the same client but via JAVASCRIPT, i don's see this messages on server. Could someone please explain why?
There is my html file
<head>
<title>Test</title>
<script src="jquery.js"></script>
<script type="application/javascript">
var ws;
function init() {
var servermsg = document.getElementById("servermsg");
ws = new WebSocket("ws://127.0.0.1:5000/");
ws.onopen = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server connected";
};
ws.onmessage = function(e){
servermsg.innerHTML = servermsg.innerHTML + "<br><< Recieved data: " + e.data;
};
ws.onclose = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server disconnected";
};
}
function postmsg(){
var text = document.getElementById("message").value;
ws.send(text);
servermsg.innerHTML = servermsg.innerHTML + "<br>>> Data sent: " + text;
}
</script>
</head>
<body onload="init();">
<form action="" onSubmit="postmsg();return false;">
<input type="text" name="message" value="" id="message">
<input type="submit" name="submit" value="" id="submit">
</form>
<div id="servermsg"><h1>Message log:</h1></div>
</body>
Thank you everyone for the help
Related
I am trying to make a quart application using multiple websockets at the same time:
<script type="text/javascript">
let socket = new WebSocket('ws://localhost:5000/mensagens/{{ dialog_id }}');
socket.onmessage = function(event) {
var messages_dom = document.getElementsByTagName('ul')[0];
var message_dom = document.createElement('li');
var cotent_dom = document.createTextNode(event.data);
message_dom.appendChild(cotent_dom);
messages_dom.appendChild(message_dom);
};
</script>
<script>
let ws = new WebSocket('ws://localhost:5000/printar/12');
function myFunction() {
var x = document.getElementById("myText").value;
ws.send(x);
document.getElementById("demo").innerHTML = x;
};
</script>
And this is the server side:
#Quart
from quart import Quart, render_template, url_for, websocket, redirect, request
#asyncio
import asyncio
app = Quart(__name__)
...
#websocket da conversa individual
#app.websocket('/mensagens/<dialog_id>')
async def mensagens(dialog_id):
print("123");
try:
output = await ".....function that updates from the SQLite database....";
await websocket.send(f"{output}");
await asyncio.sleep(1);
except Exception as e:
print("-------");
print(e);
#websocket de enviar mensagens
#app.websocket('/printar/<dialog_id>')
async def printar(dialog_id):
print("aqui");
try:
while True:
print(dialog_id);
data = await websocket.receive();
print(data + "\n=====");
except Exception as e:
print(e);
if __name__ == "__main__":
try:
app.run();
except KeyboardInterrupt:
print("=====\nAdeus!\n=====");
except Exception as e:
print(e);
However, for some reason, the second websocket only begin to run after the first websocket receives an update from "mensagens". I really don't understand what and why is happening.
Is there an example of a chat server made with Quart that I could look at?
So... I am idiot. I just found this where explains the user of receive and send indepedently (also, I am not that good with asyncio).
Anyway, here is an example:
<!doctype html>
<html>
<head>
<title>Quart + SQLite</title>
</head>
<body>
<h1>Testes!</h1>
<div class="mensagens">
<ul></ul>
</div>
Mensagem: <input type="text" id="myText" value="Mickey">
<p>Escreva suas mensagens acima!</p>
<button onclick="myFunction()">Enviar</button>
<p id="demo"></p>
<script>
let socket = new WebSocket('ws://localhost:5000/ws/12');
function myFunction() {
var x = document.getElementById("myText").value;
socket.send(x);
document.getElementById("demo").innerHTML = x;
};
socket.onmessage = function(event) {
var messages_dom = document.getElementsByTagName('ul')[0];
var message_dom = document.createElement('li');
var cotent_dom = document.createTextNode(event.data);
message_dom.appendChild(cotent_dom);
messages_dom.appendChild(message_dom);
};
</script>
</body>
</html>
And here is the python side:
#https://pgjones.gitlab.io/quart/how_to_guides/websockets.html
#Quart
from quart import Quart, render_template, url_for, websocket, redirect, request
import asyncio
app = Quart(__name__)
async def sending():
while True:
await websocket.send('f{1}');
asyncio.sleep(1);
async def receiving():
while True:
data = await websocket.receive();
print(data + "\n=====");
#app.websocket('/ws/<num>')
async def ws(num):
print(num);
producer = asyncio.create_task(sending());
consumer = asyncio.create_task(receiving());
await asyncio.gather(producer, consumer);
#app.route('/')
async def main():
return await render_template('teste_html.html');
if __name__ == '__main__':
try:
app.run();
except KeyboardInterrupt:
print("=====\nAdeus!\n=====");
except Exception as e:
print(e);
I'm trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view:
<!-- chat/templates/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<button id="chat-message-submit" type="submit" value="Send">Send</button>
</body>z
<script>
var roomName = {{ room_name_json }};
var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
console.log("got to onmessage");
var data = JSON.parse(e.data);
var message = data['message'];
document.getElementById('chat-log').value += (message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.getElementById('chat-message-submit').click();
}
};
document.getElementById('chat-message-submit').onclick = function(e) {
var messageInputDom = document.getElementById('chat-message-input');
var message = messageInputDom.value;
console.log("got message : " + message);
chatSocket.send(JSON.stringify({
'message': message
}));
console.log("This was done?");
messageInputDom.value = '';
};
</script>
</html>
Here is my consumer view :
from channels.generic.websocket import WebsocketConsumer
import json
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def recieve(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
self.send(text_data = json.dumps({
'message' : message
}))
I'm so stupid I literally made a typo, used function name "received" instead of "recieved". Thanks I'll go cry in the corner now.
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.
First I built a websocket server using node js and ws module. Then using chrome and firefox, I connect to that server and the connection is successfully established. However, the message I send from browsers does not arrive at the server. I have some code on server to console.log out if message is received. Nothing appears, however when I refresh the browser, the messages I previously sent arrive. The messages did not arrive when sent them but only once I refresh the page. I don't know why. This seems to work in from some other computers but not mine.
Here is the server code:
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express();
app.use(express.static(__dirname + '/views'));
var rmi = require('./RMIClient.js');
console.log(rmi);
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
// from here is the logic codes
var clients = [];
var clientId = 0;
wss.on('connection', function(ws) {
console.log("connection established for client "+ (clients.length+1));
clients.push(ws);
console.log("index is " + clients.indexOf(ws));
clientId += 1;
ws.send("Hello Client: " + clientId);
//
// ws.send("Welcome from AMTT Chatting Server");
ws.on('message',function(data){
console.log('message receieved : '+data);
for(var i = 0;i<clients.length;i++){
clients[i].send(data);
}
});
ws.on('a',function(){
console.log("a event fire from client");
});
ws.on('close', function() {
var index = clients.indexOf(ws);
console.log('stopping client interval '+index);
if (index > -1) {
clients.splice(index, 1);
}
});
});
Here is the client code:
<html>
<script>
//var ws = new WebSocket('ws://localhost:8080/');
var messagearea,inputarea,sendButton;
var connection = new WebSocket(/*'wss://echo.websocket.org');*/'ws://192.168.8.195:8080/');
// When the connection is open, send some data to the server
console.log(connection.readyState);
connection.onopen = function () {
console.log(connection.readyState);
inputarea.disabled = false;
sendButton.disabled = false;
};
// Log errors
connection.onerror = function (error) {
console.log('sorry connection fail:' + JSON.stringify(error));
};
// Log messages from the server
connection.onmessage = function (e) {
messagearea.value = messagearea.value + '\n' + e.data;
console.log('Server: ' + e.data);
};
function sendMessage(){
if(inputarea.value !='')
connection.send(inputarea.value);
inputarea.value = '';
}
</script>
<body>
<textarea rows="15" cols="100" id="messagearea" disabled>
</textarea>
<br/>
<textarea rows="2" cols="90" id="inputarea" required autofocus>
</textarea>
<input type = 'button' value = 'send' id = 'sendbutton' onclick = "sendMessage()"/>
</body>
<script>
messagearea = document.getElementById('messagearea');
messagearea.value = '';
inputarea = document.getElementById('inputarea');
inputarea.value = '';
inputarea.disabled = true;
sendButton = document.getElementById('sendbutton');
sendButton.disabled = true;
</script>
</html>
And again I found that kind of situation when I develop that code in java and deployed in wildfly server. I am lost. I think there is something concerned with my network card. Because that same code work perfectly in my friend's machine.
Does anybody experience this situation ? or any solution?
You can also try the following:
connection.addEventListener("message", function (e) {
processSocketMessage(e);
});
good luck :)
I am trying to send string/text data from browser client to python server and simply print it out. I have followed several examples on the internet, and all are the same: by using javascript
web_socket.send("text to be sent")
and (python)
data = web_socket.recv(1024)
print data
they receive what they want, what is clear and nice printout "text to be sent" on server site.
You can find my .html and .py below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="jquery.js"></script>
<script type="application/javascript">
var ws;
function init() {
var servermsg = document.getElementById("servermsg");
ws = new WebSocket("ws://127.0.0.1:9877/");
ws.onopen = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server connected";
};
ws.onmessage = function(e){
servermsg.innerHTML = servermsg.innerHTML + "<br><< Recieved data: " + e.data;
};
ws.onclose = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server disconnected";
};
}
function postmsg(){
var text = document.getElementById("message").value;
ws.send(text);
servermsg.innerHTML = servermsg.innerHTML + "<br>>> Data sent: " + text;
}
//$(function(){
// var text = document.getElementById("message").value;
// ws.send(text);
// servermsg.innerHTML = servermsg.innerHTML + "<br>Sent: " + text;
//});
</script>
</head>
<body onload="init();">
<form action="" onSubmit="postmsg();return false;">
<input type="text" name="message" value="" id="message">
<input type="submit" name="submit" value="" id="submit">
</form>
<div id="servermsg"><h1>Message log:</h1></div>
</body>
</html>
Server:
#!/usr/bin/env python
import socket
import threading
import struct
import hashlib
import base64
PORT = 9877
_address = ""
def create_handshake_resp(handshake):
final_line = ""
lines = handshake.splitlines()
for line in lines:
parts = line.partition(": ")
if parts[0] == "Sec-WebSocket-Key":
key = parts[2]
magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
accept_key = base64.b64encode(hashlib.sha1(key+magic).digest())
return (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " + accept_key + "\r\n\r\n")
def handle(s, addr):
data = s.recv(1024)
response = create_handshake_resp(data)
s.sendto(response, addr)
lock = threading.Lock()
while 1:
print "Waiting for data from", addr
data = s.recv(1024)
print "Done"
if not data:
print "No data"
break
print 'Data from', addr, ':', data
print 'Client closed:', addr
lock.acquire()
clients.remove(s)
lock.release()
s.close()
def start_server():
print 'STARTING SERVER...'
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', PORT))
s.listen(1)
print 'SERVER STARTED'
while 1:
conn, addr = s.accept()
print 'NEW CONNECTION ['+str(len(clients))+'], connected by ', addr
clients.append(conn)
threading.Thread(target = handle, args = (conn, addr)).start()
clients = []
start_server()
And server printout (when input was like "AA", or "ABC"):
STARTING SERVER...
SERVER STARTED
NEW CONNECTION [0], connected by ('127.0.0.1', 43877)
Waiting for data from ('127.0.0.1', 43877)
Done
Data from ('127.0.0.1', 43877) : ����w�q
Waiting for data from ('127.0.0.1', 43877)
Done
Data from ('127.0.0.1', 43877) : ��)B�h
Waiting for data from ('127.0.0.1', 43877)
I'm working on something similar myself. The Websocket protocol mandates that the client sends all its data using a mask. This is why you see 'garbage' - it's the masked text.
https://www.rfc-editor.org/rfc/rfc6455#section-5
"a client MUST mask all frames that it
sends to the server"
Read section 5 of the protocol and all will become clear. The browser (ie the client) is just implementing the protocol as it should (when you call ws.send). You need to do your bit.
Note also that when the sever sends data to the client it must NOT mask. But it still has to supply other info before the actual data (type, length etc).
To send a message from server side to websocket client you need to do as follows:
message = bytearray([0b10000001, len(original_msg)])
for byte in bytearray(original_msg):
message.append(byte)
See a stable server to client unidirectional socket library at https://github.com/westial/SingleSocket
The problem with the junk data was the javascript code sends the masked data and you must unmask it on the server side and the server sendes the unmasked data to client side.To solve this problem see my git-hub page
[][1]https://github.com/mohanbe/web-chat