Python网络编程
1、socket编程, 类:socket
1.server端
# socket第一个参数:地址
#第二参数:传送数据形式
#第三参数:代表协议
#Linux
int socket(int domain, int type, int protocol);
domain:AF_INET:Ipv4网络协议 AF_INET6:IPv6网络协议
type : tcp:SOCK_STREAM udp:SOCK_DGRAM
protocol : 指定socket所使用的传输协议编号。通常为0.
返回值:成功则返回套接口描述符,失败返回-1。
#python
socket.socket([family[, type[, proto]]])
family : AF_INET (默认ipv4), AF_INET6(ipv6) or AF_UNIX(Unix系统进程间通信).
type : SOCK_STREAM (TCP), SOCK_DGRAM(UDP) .
proto : 一般为0或者默认
如果socket创建失败会抛出一个socket.error异常
import socket
import json as simplejson
# socket first param:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=0, fileno=None)
host = "127.0.0.1"
port = 10000
server.bind((host, port))
server.listen(1)
print("server address %s %s" % (host, port))
while True:
conn, address = server.accept()
print("get connect from %s", address)
# encode msg
msg = bytes("it is server mesg", "utf-8")
conn.sendall(msg)
# c.close()
2.client端代码
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=0, fileno=None)
host = "127.0.0.1"
port = 10000
client.connect((host, port))
while True:
# 字节流 msg
client.send(bytes('client', "utf-8"))
data, adds = client.recvfrom(65535)
# 字符串转换
print(str(data, "utf-8"))
print("%s" % adds)
2.SocketServer 服务器使用工具
TCPServer(TCP通信
UDPServer(UDP通信)
UnixStreamServer(unix进程TCP通信)
UnixDatagramServer(unix进程UDP通信)
+------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
网友评论