问题
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.
I keep getting TypeErrors.
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")
- With the client portion, I was not sure how to get a KeyboardInterupt to work in 3.X, so I killed the Try and Except portions. Any Advice?
- Also, the syntax from the example I used had multiple modules being loaded from one import import os, os.path Is this the old way of only loading os.path from os module?
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")
When I run this I get TypeError: 'str' does not support the buffer interface.
Does Python 3.4 Unix Sockets only support binary?
What is the easiest way to make this work?
Thanks in advance!
回答1:
To answer the OP's questions explicitly:
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 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".
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.
回答2:
One thing you may need to do is replace if os.path.exists("/tmp/python_unix_sockets_example"): with if os.path.exists("/tmp/python_unix_sockets_example") == True:
来源:https://stackoverflow.com/questions/23282635/python-3-x-unix-socket-example