简体   繁体   中英

How to create a simple network connection in Python?

I was wondering if anyone had any good resources or suggestions for adding network functionality to a program in Python, specifically: if the sockets module would best fit my needs, and if there are any resources that anyone has found particularly enlightening.

Background: I am trying to create a fantasy football application (in Windows) where there is a "server" program that makes the draft picks, and a "client" program (running on a remote computer, not connected through LAN) that can connect to the server and receive updates on the picks. Essentially, I would only need to transmit a string or two every minute or so.

I have done some research and it seems like many people use the built-in sockets module to accomplish tasks such as this. I don't know if this module is overkill/underkill(?) for this task, so any suggestions would be appreciated.

PS The GUI for this program will be created in Tkinter, so I'm assuming some threading will need to be implemented for the separate Tk and socket loops, but that is a separate issue unless you believe it directly affects this one.

The easiest solution would probably be to have your server just be a very basic XMLRPC server. There's a python class to do exactly that (SimpleXMLRPCServer). Then, have your clients connect to that server every couple of minutes to get updated data.

See http://docs.python.org/library/simplexmlrpcserver.html for more information

Here's a real quick-and-dirty example:

server code

from SimpleXMLRPCServer import SimpleXMLRPCServer

# for demonstration purposes, just return an ever increasing integer
score = 0
def get_scores():
    global score
    score += 1
    return score

# create server, register get_scores function
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(get_scores, "get_scores")

# start the server
server.serve_forever()

client GUI code

import Tkinter as tk
import xmlrpclib
import socket

class SampleApp(tk.Tk):
    # url of the server
    url = "http://localhost:8000"

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # initialize connection to server
        self.server = xmlrpclib.ServerProxy(self.url)

        # create GUI
        self.status = tk.Label(text="", anchor="w")
        self.label = tk.Label(text="current score: ?")
        self.status.pack(side="bottom", fill="x")
        self.label.pack(side="top", fill="both", expand=True)
        self.wm_geometry("400x200")

        # wait a second to give the GUI a chance to
        # display, then start fetching the scores 
        # every 5 seconds
        self.after(1000, self.get_latest_scores, 2000)

    def update_status(self, message=""):
        '''Update the statusbar with the given message'''
        self.status.configure(text=message)
        self.update_idletasks()

    def get_latest_scores(self, interval):
        '''Retrieve latest scores and update the UI'''
        try:
            self.update_status("connecting...")
            score = self.server.get_scores()
            self.label.configure(text="current score: %s" % score)
            self.update_status()
        except socket.error, e:
            self.update_status("error: %s" % str(e))
        self.after(interval, self.get_latest_scores, interval)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

If you don't want to use Twisted, then go with socket .

That link has examples as well.

Twisted can make this sort of thing very easy. It's not exactly lightweight though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM