简体   繁体   English

如何在Python中创建简单的网络连接?

[英]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. 我想知道是否有人有任何好的资源或建议在Python中为程序添加网络功能,特别是:如果套接字模块最符合我的需求,并且有任何人发现任何资源特别有启发性。

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. 背景:我正在尝试创建一个幻想足球应用程序(在Windows中),其中有一个“服务器”程序,用于制作选秀权,以及一个“客户端”程序(在远程计算机上运行,​​不通过LAN连接),可以连接到服务器并接收选择的更新。 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. PS这个程序的GUI将在Tkinter中创建,所以我假设需要为单独的Tk和套接字循环实现一些线程,但这是一个单独的问题,除非你认为它直接影响到这个。

The easiest solution would probably be to have your server just be a very basic XMLRPC server. 最简单的解决方案可能是让您的服务器成为一个非常基本的XMLRPC服务器。 There's a python class to do exactly that (SimpleXMLRPCServer). 有一个python类可以做到这一点(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 有关更多信息,请参见http://docs.python.org/library/simplexmlrpcserver.html

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 客户端GUI代码

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 . 如果你不想使用Twisted,那么请使用socket

That link has examples as well. 该链接也有例子。

Twisted can make this sort of thing very easy. 扭曲可以使这种事情变得非常容易。 It's not exactly lightweight though. 但它并不完全轻巧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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