Python: 404 Error when accessing page from localhost - python

I had a situation right now that is currently impeding my progress on my work.
I am trying to use Flask and Sockets together so that I can check if a certain user is connected or not before I can show a video feed on the web browser.
Here is my code below.
from flask import Flask, render_template, Response, jsonify, request
from flask_socketio import SocketIO
from camera import VideoCamera, SocketConnections
import socket
import pickle
import struct
import new_client as NC #this is a client module
app = Flask(__name__)
video_camera = None
global_frame = None
urlfor_container = ""
HOST = ''
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
s.bind((HOST, PORT))
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
c = SocketConnections('127.0.0.1',5000)
c.Establish_Connection()
conn, addr = s.accept()
print('connected workstation ', addr)
data = b'' ### CHANGED
payload_size = struct.calcsize("L") ### CHANGED
# check if the connection was accepted
app.run(host='',threaded=True)
When I run this code, everything seems to be fine.
====== RESTART: C:\CENTRALIZED_SYSTEM_FILES\OpenCV Demozz\new_cam_serv.py ======
Socket created
Socket bind complete
Socket now listening
test message should print if code was accessed
connected
connected workstation ('127.0.0.1', 59283)
* Serving Flask app "new_cam_serv" (lazy loading)
* Environment: production
[31m WARNING: This is a development server. Do not use it in a production deployment.[0m
[2m Use a production WSGI server instead.[0m
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
However when I tried to access the webpage from localhost (localhost:5000/127.0.0.1:5000), I'm receiving a " 404 Page Not Found" error. I already have a templates folder along with the index.html inside the same folder where the main module is located but every time I run this code, I still receive the 404 message.
Also, I've tried using different variations for the IP address but no luck, still 404.
Any help from you guys will be greatly appreciated. Thank you.
EDIT: I've tried create an if name=="main" statement at the bottom and then inserted this code snippet inside the clause. Then I noticed that the flask server ran successfully and I was able to browse the page again, but here is the issue. after I interrupted the execution, then that is the only time my code for the socket connection got executed.
So my question now is... is it even possible for the socket and Flask to be used at the same time?
Thank you again.

I just want to provide an update that I have found a solution to this. It is indeed possible to use both socket and Flask at the same time.
I found out that the app.run() requires a valid IP address for it to work when used with socket. The IP address from the socket and the IP address from Flask need to be the same IP address or else it won't work. I found that out when I tried to debug my script and noticed that the socket and Flask on my script are referring to different IP addresses.
So, I changed:
app.run(host='',threaded=True)
to this:
app.run(host='127.0.0.1',threaded=True)
I've tried this with other IP addresses and it is working just fine.
Thank you again, everyone.

Related

Trouble connecting Python socketio server to node js socketio client

I'm having a lot of difficulty with a very simple task. I'm attempting to set up a socket.io client in node js, which should then communicate with a local socket.io server setup in python (using the python bindings here. The issue I'm having is the server is detecting the client, but the client never seems to receive the 'connect' event. I suspect this is an issue with the way I've deployed the server asynchronously, but I'm really not sure. The code for each file is below:
server.py
import socketio
from aiohttp import web
HOST = '127.0.0.1'
PORT = 10001
# create a Socket.IO server
sio = socketio.AsyncServer(async_mode='aiohttp', logger=True, engineio_logger=True)
app = web.Application()
sio.attach(app)
#sio.on('connect')
def connect(sid, environ):
print('connect ', sid)
if __name__ == '__main__':
web.run_app(app, host=HOST, port=PORT)
client.js
const io = require('socket.io-client');
const HOST = '127.0.0.1';
const PORT = '10001';
const socket = io(`http://${HOST}:${PORT}`);
console.log('Socket instantiated!');
socket.on('connect', () => {
console.log(`socket connected: ${socket.connected}`);
});
The output I would expect is to see the server print out that the client has connected, and then for the client to print out that it has connected too. However, the client never seems to receive the 'connect' event, so never prints anything to the console.
Finally, an example of the server's output is:
Server initialized for aiohttp.
======== Running on http://127.0.0.1:10001 ========
(Press CTRL+C to quit)
1c17586e4c7e49b48abefea2fba460e6: Sending packet OPEN data {'sid': '1c17586e4c7e49b48abefea2fba460e6', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000}
connect 1c17586e4c7e49b48abefea2fba460e6
1c17586e4c7e49b48abefea2fba460e6: Sending packet MESSAGE data 0
While the client's output is annoyingly just
$ node mySocket.js
Socket instantiated!
and then it just hangs doing nothing.
I'm clearly misunderstanding something here, so thank you in advance!
Small update
I quickly tested using the python socketio client, and succesfully got an actual connection, so this should narrow it down to something I've done in the JS client.
Well, I ended up downgrading from socket.io-client 3.00 (did not see there was this major release 3 days ago) back to 2.3.1, and everything started working again! However, based on the lack of issues listed on Github, I'm guessing this is not a bug that is affecting everyone.

Socket.io in flask: Data from external source

I have a web application and need to continuously display the actions going on in the backend on the browser. I have been trying to use socket.io in Flask. But I need to get the data to be displayed from other Python modules in my project. So, I tried to make a socket connection between Flask and the external module from which I will be getting data to be displayed on the browser(without any delay).
#socketio.on('my event')
def server(message):
s = socket.socket()
print "Socket successfully created"
port = 12345
s.bind(('', port))
print "socket binded to %s" %(port)
s.listen(5)
print "socket is listening"
while True:
c, addr = s.accept()
print 'Got connection from', addr
print c.recv(1024)
emit('my response', {'data': c.recv(1024)})
c.close()
print c.recv(1024) is printing data on the console. But the same data is not getting reflected on the browser. It's throwing this error -
error: [Errno 98] Address already in use
This means it's failing at emit after print c.recv(1024). What could be going wrong?
My first doubt is if this kind of connection is allowed. I mean, can we have a socket connection created inside socket.io in Flask?
Else, what is the best solution to display the backend actions on the browser continuously using Flask? I also have the web application with Django. Any solution for my use case with either Flask or Django will be appreciated (preferably Django).
Using the answer given by Miguel, I could find an appropriate solution. In the external script, we need to create a SocketIO object as follows:
socketio = SocketIO(message_queue='redis://')
Then I can use emit to send the data to be displayed on the front end.
def fn():
socketio.emit('my response', {'data': 'ur data goes here'})
fn()
And on the frontend,
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
socket.on('my response', function(msg) {
$('#log').append('<p>Received: ' + msg.data + '</p>');
document.getElementById('<div_id>').innerHTML += msg.data + "<br>";
});
});
Finally, on the Flask server side, we need to create the SocketIO object as follows:
socketio = SocketIO(app, message_queue='redis://')
Then run Flask with socketio.run(app,host='<ip>',port=<port>)
The problem is that each time a client sends the event named my event to your server, you will try to start a new socket server on port 12345. Obviously this is only going to work the first time.
Have you seen the Emitting from an External Process section in the documentation?
The idea is that you can emit events to clients from any auxiliary process, which is exactly what you need. The solution involves installing a message queue (Redis, RabbitMQ), to which the Flask-SocketIO server and the external processes that need to have emit powers connect to.

TCP Server and Client

So i'm trying to write a TCP server and client so that when the client connects, a file is sent back from the server. Here's my code for the server:
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(10)
file_to_send = ('file_to_send.txt')
print '[*] Listening on %s:%d' % (bind_ip,bind_port)
def handle_client(client_socket):
request = client_socket.recv(1024)
print '[*] Received %s' % request
client_socket.send('')
client_socket.close(file_to_send)
while True:
client,addr = server.accept()
print '[*] Accepted connection from: %s:%d' % (addr[0],addr[1])
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
And here is my code for the client:
import socket
target_host = '0.0.0.0'
target_port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))
client.send('ACK!')
response = client.recv(4096)
print response
When the server and client are run, the server returns the error 'Only one usage of each socket address (protocol/network address/port) is normally permitted' and when the client is run I get the error ' The requested address is not valid in its context'
Does anyone know why these errors are occurring or how I might be able to fix it.
I think this is a case of inaccurate example code. The server code you posted does not cause the issue you're describing (the client code does, but we'll get to that).
Server
The issue with the server code is that you're binding to the same (address, port) twice. Whether this is from wrong indentation or wrong logic it's tough to say, but that error message comes from binding the same protocol to the same address with the same port number more than once at the same time.
The rest of the code seems fine, though you can't do client_socket.close("some string") as you're doing here. socket.close does not accept any arguments.
Client
There's a simple solution here -- just change the target_host to something reasonable. You cannot connect to 0.0.0.0. This should be the addressable IP of the server in the smallest scope possible. Presumably if this is a toy program this is something like localhost.
(N.B. you bind the server to '0.0.0.0' to tell it to accept connections going to any destination IP. You could bind the server instead to '127.0.0.1' to inform the server that it will ONLY be known as localhost and never anything else.)
I've had a similar issue before and it was that I was running old versions of the program on the same port, restarting the PC or closing the processes in task manager should fix it.
I'm aware that this was asked over a year ago, so OP has probably restarted their PC since then, but hopefully this will help someone looking for a solution for a similar problem.

Problems running python program with srvany.exe

I must preface this with a full disclaimer that i'm very early in my python development days
I've made a simple python program that waits for a socket connection to the local ip address over port 20000. When it gets a connection, it pops up a message alert using the win32api.
#tcpintercomserver.py
import socket
import sys
import win32api
ip = socket.gethostbyname(socket.gethostname())
#socket creation
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Binding
server_address = (ip, 20000)
sock.bind(server_address)
print server_address
#Listen
sock.listen(1)
while True:
# Wait for a connection
connection, client_address = sock.accept()
win32api.MessageBox(0,'MessageText','Titletext', 0x00001000)
# Close Connection
connection.close()
I also have a mated client program that simply connects to the socket. The script takes an argument of the host you're trying to reach (DNS name or ip address)
#tcpintercomcli.py
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (sys.argv[1], 20000)
sock.connect(server_address)
This all runs fine as scripts. I then used CX_Freeze to turn them into executables. Both run just like they did when they were scripts.
Now i've taken the server script and connected it to a service with srvany.exe and use of the SC command in windows.
I set up the service using SC create "intercom" binPath= "C:\dist\srvany.exe"
Under the intercom service key in the registry, i've added the Parameter's key, and under there set Application to a string value c:\dist\tcpintercomserver.exe
I then perform a "net start intercom" and the service launches successfully, and the tcpintercomserver.exe is listed as a running process. However, when i run the tcpintercomcli.py or tcpintercomcli.exe, no alert comes up.
I'm baffled...is there something with the CX_Freeze process that may be messing this up?
Service process cannot show messagebox, they don't have access to UI, they usually run as SYSTEM user. if you are running from service, proper way of debugging and showing messages are using EventLog.
See:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28VS.71%29.aspx
If you are on Windows Vista or later, your script is running headlong into Session 0 Isolation -- where GUI elements from a Windows service are not shown on an interactive user's desktop.
You will probably see your message box if you switch to session 0...

Both server and the client in the same program in python

Can both a client and a server be run in the same program at the same time in Python. I want to connect a client to an external server and a server to receive messages from that external server at the same time. Whenever my server receives message from that external server my client should send messages to that external server accordingly.
Following is the way I tried to achieve that ( Just the connecting part)
import select
import socket
host = 'localhost'
portClient = 6000
portServer = 7000
backlog = 5
size = 1024
client = socket.socket()
server = socket.socket()
client.connect((host,portClient))
client.send('#JOIN')
server.bind((host,portServer))
server.listen(backlog)
running = 1
while running:
c,address = server.accept()
c.close()
client.close()
server.close()
When I run this code, no response from the external server comes.
When the while loop is omitted. I get an error saying that our server has actively refused to accept the external server.
Can I achieve this by using Python select module or Threading module? Or is there a better way?
TCP socket is a bi-directional stream of bytes. You can, and should, do all your communication with the server over the same single socket.

Categories

Resources