Python socket 使用方法如下
socket = socket.socket(family, type[, protocal])
- family代表地址家族,一般为AF_UNIX,AF_INET和AF_INET6。AF_UNIX用于同一台机器上的进程通信,AF_INET用于IPV4协议的TCP和UDP,AF_INET6用于IPV6协议;
- type代表套接字类型,一般为SOCK_STREAM,SOCK_DGRAM和SOCK_RAW。SOCK_STREAM为流式套接字,用于TCP通信,SOCK_DGRAM为数据报式套接字,用于UDP通信,SOCK_RAW为原始套接字,可以用于处理ICMP、IGMP等网络报文,这是普通套接字无法处理的;
- protocal代表协议编号,默认为0。
服务器端:
import socket
import os
if __name__ == '__main__':
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if os.path.exists("/tmp/test.sock"):
os.unlink("/tmp/test.sock")
server.bind("/tmp/test.sock")
server.listen(0)
while True:
connection, address = server.accept()
connection.send("test: %s"% connection.recv(1024))
connection.close()
客户端:
import socket
import os
if __name__ == '__main__':
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect("/tmp/test.sock")
instr = raw_input()
client.send(instr)
print client.recv(1024)
client.close()
服务器端:
import socket
import os
if __name__ == '__main__':
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 8888))
server.listen(0)
while True:
connection, address = server.accept()
connection.send("test: %s"% connection.recv(1024))
connection.close()
客户端:
import socket
import os
if __name__ == '__main__':
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 8888))
instr = raw_input()
client.send(instr)
print client.recv(1024)
client.close()
参考文档
1. http://yangrong.blog.51cto.com/6945369/1339593
2. http://blog.csdn.net/yuxi2046/article/details/6996105
3. http://blog.csdn.net/sealyao/article/details/4704876
4. http://baiying.blog.51cto.com/1068039/1112997