Python 3.X Unix Socket Example

I searched the past couple of hours looking for a simple Socket Server / Client Unix example. I found examples for Python 2.X, but I cannot find one that works for Python 3.X.

I keep getting TypeErrors.

An example I worked with:

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 side, I was not sure how to make KeyboardInterupt work in 3.X, so I killed the Try and Except parts. Any advice?
  • In addition, the syntax from the example I used contained several modules loaded from a single import import os, os.path. Is this an old way to load os.path from an 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 a 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!

+4
2

OP :

  • "TypeError: 'str" ". / .

  • Unix , , Python 3+ ↔ , (Python 3 (.4) )) Unix "".

  • : @jmhobbs, : .encode() , client.send() .decode() , server.recv() .

0

, , , os.path.exists( "/tmp/python_unix_sockets_example" ): if os.path.exists( "/tmp/python_unix_sockets_example" ) == True:

-2

Source: https://habr.com/ru/post/1537983/


All Articles