簡體   English   中英

如何在Python中創建簡單的網絡連接?

[英]How to create a simple network connection in Python?

我想知道是否有人有任何好的資源或建議在Python中為程序添加網絡功能,特別是:如果套接字模塊最符合我的需求,並且有任何人發現任何資源特別有啟發性。

背景:我正在嘗試創建一個幻想足球應用程序(在Windows中),其中有一個“服務器”程序,用於制作選秀權,以及一個“客戶端”程序(在遠程計算機上運行,​​不通過LAN連接),可以連接到服務器並接收選擇的更新。 基本上,我只需要每分鍾左右發送一兩個字符串。

我做了一些研究,似乎很多人使用內置套接字模塊來完成這樣的任務。 我不知道這個模塊是否適用於此任務是否過度/不足(?),因此任何建議都將受到贊賞。

PS這個程序的GUI將在Tkinter中創建,所以我假設需要為單獨的Tk和套接字循環實現一些線程,但這是一個單獨的問題,除非你認為它直接影響到這個。

最簡單的解決方案可能是讓您的服務器成為一個非常基本的XMLRPC服務器。 有一個python類可以做到這一點(SimpleXMLRPCServer)。 然后,讓您的客戶端每隔幾分鍾連接到該服務器以獲取更新的數據。

有關更多信息,請參見http://docs.python.org/library/simplexmlrpcserver.html

這是一個真實的快速和骯臟的例子:

服務器代碼

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()

客戶端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()

如果你不想使用Twisted,那么請使用socket

該鏈接也有例子。

扭曲可以使這種事情變得非常容易。 但它並不完全輕巧。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM