【问题标题】:Python efficient socket communicationPython 高效的套接字通信
【发布时间】:2015-05-30 20:00:56
【问题描述】:

我最近开始制作一个纯 Skype 解析器,在一切正常之后,我坚持使用套接字通信。

让我解释一下

我正在使用 python 获取用户的 IP,然后脚本打开一个套接字服务器并将用户名发送到另一个用 .NET 编写的程序

这是为什么呢?好吧,python skype API 不是那么强大,所以我使用 axSkype 库来收集更多信息。

问题

python 套接字按应有的方式发送用户名,但我不知道获取信息的最有效方法。我正在考虑在同一个脚本中打开一个套接字服务器,然后等待 .NET 程序发回的内容。

我真的不知道如何尽可能快地做到这一点,所以我请求你的帮助。

代码

class api:
  def GET(self, username):
    skypeapi.activateSkype(username)
    time.sleep(1) # because skype is ew
    buf = []
    print("==========================")
    print("Resolving user " + username)
    #This is where i'm starting the socket and sending data
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("127.0.0.1", 5756))
    s.sendall(username)
    s.close()
    #at this poaint i want to get data back from the .NET app
    for logfile in glob.glob('*.log'):
        buf += logparse.search(logfile, username)
    print("Done!")
    print("==========================")
    return json.dumps(buf)

class index:
 def GET(self):
    return render.index()

if __name__ == "__main__":
   app.run()

【问题讨论】:

  • 看看 Python 发行版中的 ftplib.py,它有很好的套接字使用示例。通常,您从套接字f = s.makefile('rb') 打开一个文件指针,然后从中读取数据。祝你好运。

标签: python sockets


【解决方案1】:

您可以将您的套接字绑定到连接。这样,您的套接字流将保持打开状态,您将能够轻松地发送和接收信息。将此与_thread 模块集成,您将能够处理多个流。这是一些将套接字绑定到流的示例代码,并且只将客户端发送的任何内容发回(尽管在您的情况下,您可以发送任何必要的数据)

import socket
from _thread import *

#clientHandle function will just receive and send stuff back to a specific client.
def clientHandle(stream):
    stream.send(str.encode("Enter some stuff: "))
    while True:
        #Here is where the program waits for a response. The 4000 is a buffer limit.
        data = stream.recv(4000)
        if not data:
           #If there is not data, exit the loop.
           break
        stream.senddall(str.encode(data + "\n"))

        #Creating socket.
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = "" #In this case the host is the localhost but you can put your host
        port = 80
        try:
            #Here the program tries to bind the socket to the stream.
            s.bind((host, port))
        except socket.error as e:
            print("There was an error: " + str(e))

        #Main program loop. Uses multithreading to handle multiple clients.
        while True:
            conn, addr = s.accept()
            print("Connected to: " + addr[0] + ": " + str(addr[1]))
            start_new_thread(clientHandle,(conn,))

现在,在您的情况下,您可以将其集成到您的 api 类中(这是您要集成的地方吗?如果我错了,请纠正我。)。所以现在当你定义和绑定你的套接字时,使用这个代码:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))

在你的情况下,host127.0.0.1,换句话说,你的本地主机,也可以通过socket.gethostbyname(socket.gethostname()) 访问(但这有点冗长),然后是port,这适合你是5756。绑定套接字后,您必须通过以下语法接受连接:

conn, addr = s.accept()

然后您可以将connaddr 传递给任何函数或仅在任何其他代码中使用。

无论你用什么来接收数据,你都可以使用socket.recv() 并传递一个缓冲区限制。 (记得对收到的任何内容进行解码。)当然,您可以使用socket.sendall() 发送数据。

如果你将它与_thread 模块结合起来,如上图所示,你可以处理多个api请求,这在未来会派上用场。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 2020-07-15
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多