python网络编程
socket.AF_UNIX unix本机进程间通信
socket.AF_INET IPV4
socket.AF_INET6 IPV6
socket.SOCK_STREAM #for tcp
socket.SOCK_DGRAM #for udp
socket.SOCK_RAW #原始套接字
socket.SOCK_RDM #可靠的udp形式
一个简单例子:
import socket
server = socket.socket()
server.bind(('localhost',6969))
server.listen()
print("开始等电话")
conn,addr = server.accept()
print("电话来了",conn)
data = conn.recv(1024)
print("recv:",data)
conn.send(data.upper())
server.close()
import socket
client=socket.socket()
client.connect(('localhost',6969))
client.send(b"hello world")
data = client.recv(1024)
print("recieve data %s"%data)
client.close()
进一步,通过循环,实现同时接受多个client,顺序接受数据
import socket
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print("开始等电话")
while True:
conn,addr = server.accept()
print("电话来了",conn)
while True:
data = conn.recv(1024)
print("recv:",data)
if not data:
print("client has lost...")
break
conn.send(data.upper())
server.close()
import socket
client=socket.socket()
client.connect(('localhost',6969))
while True:
msg = input(">>:".strip())
if len(msg) == 0: continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print("recieve data:",data.decode())
client.close()
稍微改一下:
import socket,os
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print("开始等电话")
while True:
conn,addr = server.accept()
print("电话来了",conn)
while True:
data = conn.recv(1024)
print("recv:",data)
if not data:
print("client has lost...")
break
res = os.popen(data.decode('utf-8')).read()
conn.send(res.encode('utf-8'))
server.close()
import socket
client=socket.socket()
client.connect(('localhost',6969))
while True:
msg = input(">>:".strip())
if len(msg) == 0: continue
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print("recieve data:",data.decode())
client.close()
进一步,传输文件: