1、socket() 模块函数
创建套接字语法:
socket(socket_family, socket_type, protocol = 0)
socket_family 用 AF_INET 表示网络连接
socket_type 是 SOCKET_STREAM (为创建 TCP 套接字)或 SOCKET_DGRAM(为创建 UDP 套接字)
protocol 通常省略,默认是 0
为创建 TCP/IP 连接 ,可以用以下方式
tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
为创建 UDP/IP 连接,可以用以下方式
udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2、套接字对象(内置)方法
3、创建 TCP 服务端
from socket import *
from time import ctime
host = ''
port = 8433
address = (host, port)
bufsize = 1024
tcpServer = socket(AF_INET, SOCK_STREAM)
tcpServer.bind(address)
tcpServer.listen()
while True:
print('waiting for connection ...')
tcpCliSock, Addr = tcpServer.accept()
print('connected from:', Addr)
while True:
data = tcpCliSock.recv(bufsize)
if not data:
break
tcpCliSock.send(ctime().encode('utf-8'))
tcpCliSock.close()
tcpServer.close()
4、创建 TCP 客户端
from socket import *
from time import ctime
host = 'localhost'
port = 8433
address = (host, port)
bufsize = 1024
tcpClient = socket(AF_INET, SOCK_STREAM)
tcpClient.connect(address)
while True:
print('client is connecting')
data = '324242'
tcpClient.send(data.encode('utf-8'))
data = tcpClient.recv(bufsize)
if not data:
break;
print(data.decode('utf-8'))
tcpClient.close()
5、创建 UDP 服务端
from socket import *
from time import ctime
host = ''
port = 3528
address = (host, port)
bufsize = 1024
udpSoc = socket(AF_INET, SOCK_DGRAM)
udpSoc.bind(address)
while True:
print('udpServer start ')
udpSockServer, addr = udpSoc.recvfrom(bufsize)
print('udpServer add : ', addr)
udpSoc.sendto(ctime().encode('utf-8'), addr)
udpSoc.close()
6、创建 UDP 客户端
from time import ctime
from socket import *
host = 'localhost'
port = 3528
address = (host, port)
bufsize = 1024
udpSocClient = socket(AF_INET, SOCK_DGRAM)
while True:
print('udpClient start')
udpSocClient.sendto('dadasda'.encode('utf-8'), address)
data, addr = udpSocClient.recvfrom(bufsize)
if not data:
break
print(data)
udpSocClient.close()