Answer the question
In order to leave comments, you need to log in
How to issue a log on a remote computer through sockets?
Faced the following task: There is a server to which clients are connected through a websocket. One client is a remote computer that connects to the server when the HTML file is opened. An HTML file that, using JS, connects to the server via a socket and simply displays each message received from it. The code:
<!DOCTYPE html>
<html>
<head>
<title>SGW UI</title>
</head>
<body>
<script>
var ws = new WebSocket("ws://130.83.40.174:5678/"),
messages = document.createElement('ul');
ws.onmessage = function (event) {
var messages = document.getElementsByTagName('ul')[0],
message = document.createElement('li'),
content = document.createTextNode(event.data);
message.appendChild(content);
messages.appendChild(message);
};
document.body.appendChild(messages);
</script>
</body>
</html>
#!/usr/bin/python3.4
import asyncio
#!/usr/bin/python3.4
import datetime
import random
import websockets
import sys
browser_client = None
@asyncio.coroutine
def socket_handler(websocket, path):
global browser_client
if(browser_client is None):
browser_client = websocket
else:
m = yield from websocket.recv()
browser_client.send(m)
start_server = websockets.serve(socket_handler, '130.83.40.174', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
browser_client = None
messages = []
@asyncio.coroutine
def socket_handler(websocket, path):
global browser_client
if(browser_client is None):
while True:
if(len(messages) > 0):
msg = messages.pop()
yield from websocket.send(msg)
else:
m = yield from websocket.recv()
messages.append(m)
#!/usr/bin/env python
import asyncio
import websockets
@asyncio.coroutine
def hello():
websocket = yield from websockets.connect(u'ws://130.83.40.174:5678')
name = "Test"
yield from websocket.send(name)
yield from websocket.close()
asyncio.get_event_loop().run_until_complete(hello())
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question