Python 3.X Unix 套接字示例 [英] Python 3.X Unix Socket Example

查看:55
本文介绍了Python 3.X Unix 套接字示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几个小时我一直在寻找一个简单的服务器/客户端 Unix 套接字示例.我已经找到了 Python 2.X 的示例,但我没有找到适用于 Python 3.X 的示例.

I have been searching the last couple of hours on finding a simple Server / Client Unix Socket Example. I have found examples for Python 2.X, but I am failing at finding one that works for Python 3.X.

我不断收到类型错误.

我一直在使用的示例是:

The example that I have been working with is:

client.py

# -*- coding: utf-8 -*-
import socket
import os
# import os, os.path

print("Connecting...")
if os.path.exists("/tmp/python_unix_sockets_example"):
    client = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM )
    client.connect("/tmp/python_unix_sockets_example")
    print("Ready.")
    print("Ctrl-C to quit.")
    print("Sending 'DONE' shuts down the server and quits.")
    while True:
#        try:
            x = input( "> " )
            if "" != x:
            print("SEND:", x)
                client.send( x )
                if "DONE" == x:
                    print("Shutting down.")
                break
#        except KeyboardInterrupt, k:
#            print("Shutting down.")
    client.close()
else:
    print("Couldn't Connect!")
    print("Done")

  • 对于客户端部分,我不确定如何让 KeyboardInterupt 在 3.X 中工作,所以我取消了 Try 和 except 部分.有什么建议吗?
  • 此外,我使用的示例中的语法从一个导入加载了多个模块导入 os, os.path这是仅从 os 模块加载 os.path 的旧方法吗?
  • server.py

    # -*- coding: utf-8 -*-
    
    import socket
    import os
    # import os, os.path
    # import time
    
    if os.path.exists("/tmp/python_unix_sockets_example"):
        os.remove("/tmp/python_unix_sockets_example")
    
    print("Opening socket...")
    server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    server.bind("/tmp/python_unix_sockets_example")
    
    print("Listening...")
    while True:
        datagram = server.recv(1024)
    
        if not datagram:
            break
        else:
            print("-" * 20)
            print(datagram)
            if "DONE" == datagram:
                break
    print("-" * 20)
    print("Shutting down...")
    server.close()
    os.remove("/tmp/python_unix_sockets_example")
    print("Done")
    

    • 当我运行它时,我得到 TypeError: 'str' 不支持缓冲区接口.

      • When I run this I get TypeError: 'str' does not support the buffer interface.

        Python 3.4 Unix Sockets 是否只支持二进制?

        Does Python 3.4 Unix Sockets only support binary?

        完成这项工作的最简单方法是什么?

        What is the easiest way to make this work?

        提前致谢!

        推荐答案

        明确回答 OP 的问题:

        To answer the OP's questions explicitly:

        1. TypeError: 'str' 不支持缓冲区接口"错误是由尝试通过字节接口发送/接收字符串编码数据引起的.

        1. The "TypeError: 'str' does not support the buffer interface" error was caused by attempting to send/receive string-encoded data over a bytes interface.

        Unix 套接字不了解编码,它们传递原始字节,并且 Python 3+ 不再为您执行任何魔术字节<->编码的字符串转换,因此从这个意义上说是的,(Python 3(.4)) Unix 套接字仅支持二进制".

        Unix sockets have no knowledge of encodings, they pass raw bytes, and Python 3+ no longer does any magic bytes<->encoded string conversions for you, so in this sense yes, (Python 3(.4)) Unix sockets only support "binary".

        使其工作的最简单方法是@jmhobbs 在他上面链接的要点中展示的:当 client.send() 发送字符串时,您必须将字符串 .encode() 转换为字节,并且 .decode()当 server.recv() 处理它们时,字节返回到字符串.

        The easiest way to make it work was as @jmhobbs demonstrated in his above-linked gist: you must .encode() your strings to bytes when client.send()'ing them and .decode() the bytes back to strings when server.recv()'ing them.

        这篇关于Python 3.X Unix 套接字示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆