Created
November 16, 2012 15:27
-
-
Save quiver/4088192 to your computer and use it in GitHub Desktop.
Linux Programming Interface 57.2 Stream Sockets in the UNIX Domain(in Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ python us_xfr_sv.py > b & | |
[1] 1553 | |
$ cat *py > a | |
$ python us_xfr_cl.py < a | |
$ kill %1 | |
[1]+ Terminated python us_xfr_sv.py > b | |
$ diff -u a b | |
$ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The Linux Programming Interface Listing 57-4: A simple UNIX domain stream socket client | |
# Python port of sockets/us_xfr_cl.c | |
import socket | |
import sys | |
def main(): | |
sfd = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) | |
sv_sock_path = '/tmp/us_xfr' | |
try: | |
sfd.connect(sv_sock_path) | |
except socket.error: | |
sys.exit('connect') | |
while True: | |
try: | |
buff = raw_input() | |
except EOFError: | |
break | |
try: | |
sfd.send(buff + '\n') | |
except socket.error: | |
sys.exit('send') | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The Linux Programming Interface Listing 57-3: A simple UNIX domain stream socket server | |
# Python port of sockets/us_xfr_sv.c | |
import os | |
import socket | |
import sys | |
BACKLOG = 5 | |
def main(): | |
sfd = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) | |
sv_sock_path = '/tmp/us_xfr' | |
if os.path.exists(sv_sock_path): | |
os.remove(sv_sock_path) | |
try: | |
sfd.bind(sv_sock_path) | |
except socket.error: | |
sys.exit('bind') | |
try: | |
sfd.listen(BACKLOG) | |
except socket.error: | |
sys.exit('listen') | |
while True: | |
cfd, addr = sfd.accept() | |
while True: | |
data = cfd.recv(1024) | |
if not data: | |
break | |
sys.stdout.write(data) | |
sys.stdout.flush() | |
cfd.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment