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!