首页 > 学院 > 开发设计 > 正文

UNIX下的通信

2019-11-11 05:08:29
字体:
来源:转载
供稿:网友

今天继续往后读了一点,进度非常慢,可能是理解不深刻。先记录下今天学到的一些东西

UNIX套接字

查阅了一下,unix套接字用于计算机内部的交流。其地址是文件路径 且需要在unix/linux下 我是在unbunta下实现的。代码依旧来自《python标准库》

import socketimport sysimport osserver_adress = './uds_socket'try: os.unlink(server_adress)except OSError: if os.path.exists(server_adress): raisesock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)PRint >>sys.stderr,'starting up on %s' %server_adress sock.bind(server_adress)sock.listen(1)while True: print >>sys.stderr,'waiting for a connection' connection ,client_address = sock.accept() try: print >>sys.stderr,'connection from',client_address while True: data = connection.recv(16) print >>sys.stderr,'recived "%s"' %data if data: print >>sys.stderr,'sending data back to the client ' connection.sendall(data) else: print >>sys.stderr,'no data from %s'%client_address break finally: connection.close()

下面是client端的 import socket import sys

sock = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)server_address = './uds_socket'print >>sys.stderr,'connecting to %s'%server_addresstry: sock.connect(server_address)except socket.error,msg: print >>sys.stderr,msg sys.exit(1)try: message = 'This is the message.It will be repeated.' print >>sys.stderr,'sending "%s"' %message sock.sendall(message) amount_received = 0 amount_expected = len(message) while amount_received < amount_expected: data = sock.recv(16) amount_received+=len(data) print >>sys.stderr,'received "%s"'%datafinally: sock.close()

与之前的程序差异不大,很明显发现遵循以下几步 服务器: 1.先选择所需服务的套接字,例如 sock = socket(socket.AF_INET,socket.SOCK_STREAM) 这个是tcp 2绑定 3监听 4创建连接 5关闭 客户端: 1如上第一步 2连接 以上是最近总结的一些东西


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表