Here is the code:
server part and called from machine 10.42.0.1:
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ()
server = SimpleXMLRPCServer(('10.42.0.1', 8000),
requestHandler=RequestHandler)
server.register_function(adder, 'add')
print('initialize finish')
server.serve_forever()
client part, and call from machine 10.42.0.2:
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://10.42.0.1:8000')
print(s.add(2,3))
However, I've got the error message from machine 10.42.0.2:
ConnectionRefusedError: [Errno 111]. And telnet 10.42.0.1 8000 also failed.
Then, I change this sentence:
server = SimpleXMLRPCServer(('10.42.0.1', 8000),
requestHandler=RequestHandler)
to:
server = SimpleXMLRPCServer(('', 8000),
requestHandler=RequestHandler)
And restart xmlrpc server, the xmlrpc client works this time. Then I change this sentence to:
server = SimpleXMLRPCServer(('10.42.0.1', 8001),
requestHandler=RequestHandler)
And open a new xmlrpc server, and change the client code to:
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://10.42.0.1:8001')
print(s.add(2,3))
And start a new xmlrpc client, the client now also works.
Anyone help me explain this strange phenomenon?
A bit like arp table not built.
Related
I've created a single socket endpoint on the server side that looks like this:
Server.py
from client import sockio_client
from flask_socketio import SocketIO
from flask import Flask
app = Flask(__name__)
socketio = SocketIO(app)
#socketio.on('status_update')
def status_update(data):
print('got something: ',data)
#app.before_first_request
def start_ws_client():
# now that server is started, connect client
sockio_client.connect('http://localhost:5000')
if __name__ == "__main__":
socketio.run(app,debug=True)
And the corresponding client:
Client.py
import socketio
from threading import Thread
sockio_client = socketio.Client()
# wait to connect until server actually started
# bunch of code
def updater():
while True:
sockio_client.emit('status_update', 42)
time.sleep(10)
t = Thread(target=updater)
t.start()
I've got a single background thread running outside of the server and I would like to update clients with the data it periodically emits. I'm sure there is more than one way to do this, but the two options I came up with were to either (i) pass a reference to the socketio object in server.py above to the update function in client by encapsulating the update function in an object or closure which has a reference to the socketio object, or (ii) just use a websocket client from the background job to communicate to the server. Option one just felt funny so I went with (ii), which feels... okish
Now obviously the server has to be running before I can connect the client, so I thought I could use the before_first_request decorator to make sure I only attempt to connect the client after the server has started. However every time I try, I get:
socketio.exceptions.ConnectionError: Connection refused by the server
At this point the server is definitely running, but no connections will be accepted. If I were to comment out the sockio_client.connect in server.py, and connect from an entirely separate script, everything works as expected. What am I doing wrong? Also, if there are much better ways to do this, please tear it apart.
I am trying to upload/download file to local FTP server, but it gives me the error mentioned in title.
For server I am using pyftpdlib:
import os
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
# instantiate a dummy authorizer
authorizer = DummyAuthorizer()
# instantiate anonymous user to current directory
authorizer.add_anonymous(os.getcwd())
# FTP handler class
handler = FTPHandler
handler.authorizer = authorizer
# setup server on localhost, port = 21
address = ('', 21)
server = FTPServer(address, handler)
# set a limit for connections
server.max_cons = 10
server.max_cons_per_ip = 3
# start ftp server
server.serve_forever()
Here is client code:
from ftplib import FTP
# connect to FTP server
client = FTP(host="127.0.0.1")
client.login()
# list the contents of directory
client.retrlines('LIST')
But the FTP constructor throws:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it.
Initially I thought it was port issue (I did not specify port from client when connected), so changed server port to 21, which I believe is default port.
When running server code, I get firewall alert, but when I give it the permission it runs normally. How can I connect to server from the client side?
I'm not sure what '' as an address would do on the server side. Either it is a wrong value in the first place. Or it may resolve to a different IP address than the 127.0.0.1. You should use the same value both on server and client side.
I'd start with 127.0.0.1 on the server side.
address = ('127.0.0.1', 21)
I'm a little over my head when it comes to this SSH thing. Basically I am trying to access a friends server through and SSH tunnel using twisted conch. He has given me the following information:
MONGO_HOST = "ip address"
MONGO_DB = "server name"
MONGO_USER = "user name"
MONGO_PASS = "server password"
I was able to get this information to work using the python library motor.motor_asyncio (I need this be async compatible in order to use with other libraries) but for reasons that I can get into if necessary, will not work on the raspberry pi that I plan on running this program on.
Long story short, I was wondering if anyone could help me with some sample code to access my friends server using the information given above with twisted.conch.
I looked on the twisted.conch readthedocs, but the example needs more information than I can provide (I think) and is WAY over my head in terms of networking/SSH/etc.
Thanks in advance. I am willing to put in the work, but I need to know where to look.
Here is my relevant bit of code so far:
from motor.motor_asyncio import AsyncIOMotorClient
from sshtunnel import SSHTunnelForwarder
MONGO_HOST = "host address"
MONGO_DB = "server name"
MONGO_USER = "username"
MONGO_PASS = "password"
server = SSHTunnelForwarder(
MONGO_HOST,
ssh_username=MONGO_USER,
ssh_password=MONGO_PASS,
remote_bind_address=('address', gate),
local_bind_address=('address', gate)
)
server.start()
client = AsyncIOMotorClient('address', gate)
db = client.server_name
You can forward ports with Conch like this:
rom twisted.internet.defer import Deferred
from twisted.conch.scripts import conch
from twisted.conch.scripts.conch import ClientOptions, SSHConnection
from twisted.conch.client.direct import connect
from twisted.conch.client.default import SSHUserAuthClient, verifyHostKey
from twisted.internet.task import react
def main(reactor):
# authenticate as this user to SSH
user = "sshusername"
# the SSH server address
host = "127.0.0.1"
# the SSH server port number
port = 22
# a local port number to listen on and forward
localListenPort = 12345
# an address to forward to from the remote system
remoteForwardHost = "127.0.0.1"
# and the port number to forward to
remoteForwardPort = 22
conch.options = ClientOptions()
conch.options.parseOptions([
# don't ask the server for a shell
"--noshell",
# set up the local port forward
"--localforward={}:{}:{}".format(
localListenPort,
remoteForwardHost,
remoteForwardPort,
),
# specify the hostname for host key checking
host,
])
# don't stop when the last forwarded connection stops
conch.stopConnection = lambda: None
# do normal-ish authentication - agent, keys, passwords
userAuthObj = SSHUserAuthClient(user, conch.options, SSHConnection())
# create a Deferred that will tell `react` when to stop the reactor
runningIndefinitely = Deferred()
# establish the connection
connecting = connect(
host,
port,
conch.options,
verifyHostKey,
userAuthObj,
)
# only forward errors so the reactor will run forever unless the
# connection attempt fails. note this does not set up reconnection for a
# connection that succeeds and then fails later.
connecting.addErrback(runningIndefinitely.errback)
return runningIndefinitely
# run the reactor, call the main function with it, passing no other args
react(main, [])
Some of the APIs are weird because they are CLI focused. You don't have to do it this way but port forwarding is most easily accessible with these APIs rather than the APIs that are more focused on programmatic use.
I have the intention of running machine learning algorithms written in Python on data in a database of a Ruby on Rails app. After some research I have discovered sockets and therefore created a Ruby server and Python client. I am running them both on two different command prompt terminals.
Here is the Ruby server code:
require "socket"
server = TCPServer.open(2000)
loop {
client = server.accept
client.puts(Time.now.ctime)
client.puts "Closing the connection. Bye!"
client.close
}
Here is the Python client code:
import socket
s = socket.socket()
host = "localhost"
port = 2000
s.connect((host , port))
I do not understand where the problem is. Kindly assist.
Given insightful answers to my question above the code Ruby server and Python client should be as below.
For the Ruby server:
require "socket" # Get sockets from stdlib
server = TCPServer.open("127.0.0.1" , 2000) # Socket to listen on port 2000
loop { # Server runs forever
client = server.accept # Wait for a client to connect
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
}
For the Python client:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1"
port = 2000 # Reserve a port for your service.
s.connect((host , port))
print s.recv(1024)
s.close() # Close the socket when done
The open() method of the TCPServer class in Ruby takes two parameters. The first being the host name and the second the port i.e
TCPServer.open(hostname , port)
I am running my application with Windows Azure on a Virtual Machine with ubuntu 14.04 lts. I am running my Django application through WSGI on Apache.
Previously i ran django locally with the command "python manage.py runserver", and every thing worked fine when my website connected to my sockets.py file from website.html.
I am running Django through Apache on public ip port 80
I am running the sockets.py separately in a terminal through Putty
I am reading the error through the Google Chrome console
Suddenly this error occurs: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. whenever i try to connect to the socket.
After a while my page response with: failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
website.html js:
ws = new WebSocket("ws://10.77.22.74:1339/ws");
function load_all() {
target = "load_all"
ws.send(target)
}
ws.onmessage = function(evt) {
console.log(evt.data)
}
The ip is my internal ip on my virtual machine.
sockets.py:
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
print 'new connection'
def on_message(self, message):
self.write_message(message)
def on_close(self):
print 'connection closed'
application = tornado.web.Application([
(r'/ws', WSHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(1339)
tornado.ioloop.IOLoop.instance().start()
I have tried to change the http_server.listen(1339) to http_server.listen(1339, adress='10.77.22.74') (sockets.py)
I have tried using my public ip and opening a port through tcp (endpoints) and adjusting the scripts after that (sockets.py & website.html)
I have tried running with the localhost & 127.0.0.1 (sockets.py & website.html)
I have tried with ws & wss
I still get the error for some reason, do i need to give Apache (www-data) some permissions to connect to the sockets.py?
Which IP should i use, both on socket.py and website.htm?
Solved
Turn out Tornado is listening to all IP:s if you not specify the adress in the socket server. I opened a port on the public IP and used that IP for my javascript socket connection.