Skip to content Skip to sidebar Skip to footer

Getting Some Response From A Python Socket Server

I have just started learning python and i was wondering how i would get the client to execute a function on the server and get some response Here is my server code import socket s

Solution 1:

If you simply want to call functions you should check out XMLRPC. Simple and easy, here's the example from the python documentation.

# Server codeimport xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer

defis_even(n):
    return n%2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print"Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()


# Client codeimport xmlrpclib

proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
print"3 is even: %s" % str(proxy.is_even(3))
print"100 is even: %s" % str(proxy.is_even(100))

Solution 2:

You'd have to send it some sort of message telling the server to execute this. For example you could send it a string "ADDME", when the server receives this, it stores addme()'s result and sends it back to the client which then prints it.

Solution 3:

You need to set up your own communication protocol. Invent a command that, when you send it, makes the server execute some function.

To send data over a socket (comparable to a file-like object) you need to serialize (encode) it into a set of bytes, and, after receiving these bytes on the other end, deserialize (decode) those.

Encode the function's return value to e.g. JSON in case it is dictionary, to str in case it is an integer, or invent your own binary protocol or, if you would like to be able to send almost any kind of Python object through "the wire", then pickle the return value. Send the encoded (pickled) return value to the client. It has to decode (unpickle) it then.

In any case, you will have to implement your own protocol, with its own set of commands, while each command might have arguments. You will have to find a way to separate the command from its argument and will have to (in)validate commands you receive.

For learning network communication, your task is great. For implementing a production software, you must have a look and rock-solid messaging libraries such as xmlrpclib as pointed out by others.

Solution 4:

Sounds like you are trying to implement RPC. See here for a discussion on existing libraries: What is the current choice for doing RPC in Python?

Solution 5:

This is how i did it

server.py

from xmlrpc.server import SimpleXMLRPCServer

defaddme(x,y):
    return x + y

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(addme, "addme")
server.serve_forever()

input('press enter')

client.py

import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
print("the sum: %s" % str(proxy.addme(6,4)))

input('press enter')

Post a Comment for "Getting Some Response From A Python Socket Server"