Policy Server with gevent-websocket - python

working on trying to get gevent-websocket working and it's not connecting to my policy server for the flash specification. My policy.py is as follows:
from gevent.server import StreamServer
policy = """<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
</cross-domain-policy>\0"""
def handle(sock, address):
s = sock.makefile()
while True:
msg = s.readline()
if not msg:
print("Client disconnected (%s:%s)" % address)
break
else:
sock.sendall(policy)
print("Client connected, served policy (%s:%s)" % address)
server = StreamServer(('0.0.0.0', 843), handle)
server.serve_forever()
Yet with websocket I'm getting:
[WebSocket] policy file: xmlsocket://localhost:843
[WebSocket] cannot connect to Web Socket server at ws://localhost:8065 (SecurityError: Error #2048) make sure the server is running and Flash socket policy file is correctly placed
[WebSocket] close

the readline() method won't work here, because Flash sends a '<policy-file-request/>\0' which is not terminated by newline.
Try this instead of readline():
expected = '<policy-file-request>'
s.read(len(expected))

Related

conn.send('Hi'.encode()) BrokenPipeError: [Errno 32] Broken pipe (SOCKET)

hi i make model server client which works fine and i also create separate GUI which need to two input server IP and port it only check whether server is up or not. But when i run server and then run my GUI and enter server IP and port it display connected on GUI but on server side it throw this error. The Server Client working fine but integration of GUI with server throw below error on server side.
conn.send('Hi'.encode()) # send only takes string BrokenPipeError: [Errno 32] Broken pip
This is server Code:
from socket import *
# Importing all from thread
import threading
# Defining server address and port
host = 'localhost'
port = 52000
data = " "
# Creating socket object
sock = socket()
# Binding socket to a address. bind() takes tuple of host and port.
sock.bind((host, port))
# Listening at the address
sock.listen(5) # 5 denotes the number of clients can queue
def clientthread(conn):
# infinite loop so that function do not terminate and thread do not end.
while True:
# Sending message to connected client
conn.send('Hi'.encode('utf-8')) # send only takes string
data =conn.recv(1024)
print (data.decode())
while True:
# Accepting incoming connections
conn, addr = sock.accept()
# Creating new thread. Calling clientthread function for this function and passing conn as argument.
thread = threading.Thread(target=clientthread, args=(conn,))
thread.start()
conn.close()
sock.close()
This is part of Gui Code which cause problem:
def isOpen(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
data=s.recv(1024)
if data== b'Hi':
print("connected")
return True
except:
print("not connected")
return False
def check_password(self):
self.isOpen('localhost', 52000)
Your problem is simple.
Your client connects to the server
The server is creating a new thread with an infinite loop
The server sends a simple message
The client receives the message
The client closes the connection by default (!!!), since you returned from its method (no more references)
The server tries to receive a message, then proceeds (Error lies here)
Since the connection has been closed by the client, the server cannot send nor receive the next message inside the loop, since it is infinite. That is the cause of the error! Also there is no error handling in case of closing the connection, nor a protocol for closing on each side.
If you need a function that checks whether the server is online or not, you should create a function, (but I'm sure a simple connect is enough), that works like a ping. Example:
Client function:
def isOpen(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((str(ip), int(port)))
s.send("ping".encode('utf-8'))
return s.recv(1024).decode('utf-8') == "pong" # return whether the response match or not
except:
return False # cant connect
Server function:
def clientthread(conn):
while True:
msg = conn.recv(1024).decode('utf-8') #receiving a message
if msg == "ping":
conn.send("pong".encode('utf-8')) # sending the response
conn.close() # closing the connection on both sides
break # since we only need to check whether the server is online, we break
From your previous questions I can tell you have some problems understanding how TCP socket communication works. Please take a moment and read a few articles about how to communicate through sockets. If you don't need live communications (continous data stream, like a video, game server, etc), only login forms for example, please stick with well-known protocols, like HTTP. Creating your own reliable protocol might be a little complicated if you just got into socket programming.
You could use flask for an HTTP back-end.

Implement both HTTP and HTTPS on my simple Python socket server

I want my visitors to be able to use both HTTP and HTTPS. I am using a simple Python webserver created with socket. I followed this guide: Python Simple SSL Socket Server, but it wasn't that helpful because the server would crash if the certificate cannot be trusted in one of the clients. Here is a few lines of code from my webserver that runs the server:
def start(self):
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket object to the address and port
s.bind((self.host, self.port))
# start listening for connections
s.listen(100)
print("Listening at", s.getsockname())
while True:
# accept any new connection
conn, addr = s.accept()
# read the data sent by the client (1024 bytes)
data = conn.recv(1024).decode()
pieces = data.split("\n")
reqsplit = pieces[0].split(" ");
# send back the data to client
resp = self.handleRequests(pieces[0], pieces);
conn.sendall(resp)
# close the connection
conn.close()
Have another service (something like nginx) handle the https aspect, then configure the service to reverse proxy to your python server

My socket always connect to the server even the server offline

I create a simply client and a server using python. In order to create my server I do a port forwarding. But I have a problem that I don't success to resolve, in fact no matter if the server is online or offline. My socket gives me a message of success. Where does this failure come from ?
This is my code in the client:
import socket
from threading import Thread
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client_socket.connect(("89.139.105.181", 8350))
print "Client connection success"
except socket.error:
print "Client error"
def send_to_server():
msg = raw_input("Client:")
client_socket.send(msg)
def recv_from_server():
response_server = client_socket.recv(1024)
print response_server
def main():
while True:
send_thread = Thread(target=send_to_server,)
recv_thread = Thread(target=recv_from_server,)
send_thread.start()
recv_thread.start()
send_thread.join()
recv_thread.join()
if __name__ == "__main__":
main()
As you are connecting to the intermediate node using socket which in turn forwarding you request to target node in the same network, the connection to your intermediate node will be successful even if your target node is down.
So since your client's client_socket.connect() won't be informed about whether the socket connection to target node from intermediate node was successful or not, it will always return success as it was successfully connected to the intermediate node.
But a simple hack to find out whether you were actually connected to target node would be to check whether you are actually receiving the expected response within a specified amount of time after sending the request (Assuming that for every request being sent by client, the server will be sending some response).

Communicating with multiple clients using one TCP socket python

I am using TCP sockets to communicate between my server and clients. The server code and socket code are as below:
server:
from socket import *
HOST = 'xx.xx.xx.xx'
PORT = 1999
serversocket = socket(AF_INET,SOCK_STREAM)
serversocket.bind((HOST,PORT))
print 'bind success'
serversocket.listen(5)
print 'listening'
while True:
(clientsocket, address) = serversocket.accept()
print ("Got client request from",address)
#clientsocket.send('True')
data = clientsocket.recv(1024)
print data
clientsocket.send('True')
clientsocket.close()
client:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port on the server given by the caller
server_address = ('xx.xx.xx.xx', 1999)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
try:
message = 'This is the message. It will be repeated.'
print >>sys.stderr, 'sending'
for x in range (0,1):
name=raw_input ('what is ur name')
print type(name)
sock.send(name)
print sock.recv(1024)
finally:
sock.close()
I am able to communicate with the server from client and able to send and receive data. But the problem I am facing is that I am not able to send and receive data continuously from the server. I have to restart my client code on my laptop to send and receive data again from the server. The way the above client code is working is that when I give a keyboard input, then the socket sends data to server and server responds back. But in the client code, in the for loop if I do two iterations, for the second iteration the data I enter from keyboard is not reaching server. I need to restart my client code to send data again. How do I fix this ?
Also, when once client is connected to the server, the other cannot connect to the server. Any ideas on how to do this ?
You need to design and implement a protocol that specifies what each side is supposed to do and then implement that protocol. You're expecting it to work by magic.
For example:
data = clientsocket.recv(1024)
I suspect you are expecting this to receive a "message". But TCP has no notion of messages. If you need to send and receive messages, you need to define precisely what a "message" is for your protocol and write code to send and receive them.
It may be helpful to look at the specifications for other protocols that use TCP such as HTTP, FTP, or IRC. It really is worth the time to write out a specification of your protocol before you write any code. It will save a lot of pain.

Exception not handled IOError

I can't seem to figure out why my code can't handle the exception of reporting an error if my web server does not contain a file. In the directory of my server I have the code for it and HelloWorld.html. For other files it should report an error. I'm looking through my code and it would seem that it is reading any file and just saying that its contents are blank without actually throwing an error that the file is not on the server. What is going on here?
#Tasks: Create a socket, bind to a specific address and port, send and receive an HTTP packet.
#Description: Web server should handle one HTTP request at a time. So the serve closes its TCP connection after response.
#Accept and parse the HTTP request, get the requested file from the server (i.e. HelloWorld.html), create a response
#message with the requested file and header lines, then send the response to the client.
#Error handling: If file not found then send HTTP "404 Not Found" Message back to client.
#import socket module: here we are using a low-level networking class from Python
from socket import *
#create the socket that belongs to the server.
#AF_INTET represents the address families and protocols.
#SOCK_STREAM represents the socket type
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a server socket
#Define variable for serverPort; we'll use the one in the helper page of the book
serverPort = 51350
#Define host address
serverHost = ''
#Bind the socket to the local host machine address and port
serverSocket.bind((serverHost, serverPort))
#Listen for TCP connections from the client
serverSocket.listen(1)
#Verify setup for receiving
print 'Server is ready to receive'
while True:
#Establish the connection
print 'Ready to serve...'
#When the server receive a request from the client it must establish a new connectionSocket and begin taking in the data.
connectionSocket, addr = serverSocket.accept()
try:
#Take data from connectionSocket and place in message.
#.recvfrom doesn't work because it expects data and return address variables.
message = connectionSocket.recv(1024)
#uncomment for header information
#print message
#parse the message
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read();
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
connectionSocket.send('404 Not Found')
connectionSocket.close()
#Close client socket
serverSocket.close()
Perhaps you need "HTTP/1.1 404 Not Found\r\n\r\n" instead of "404 Not Found".
Also, you seem to close serverSocket within the loop, thus next accept() fails.

Categories