创建socket
一.发送数据的流程:
1.创建套接字 socket
2.发送数据 :套接字.sendto(data.encode,('ip address', port))
3.关闭 :套接字.close()
二. 接受数据流程
1. 创建套接字
2. 绑定本地发送主机的信息(IP地址和端口号) bind(('ip address', port))
3. 接受数据 : 套接字.recvfrom(最大字节数)
4.关闭数据: 套接字.close()
在python中 使用socket模块的函数socket创建socket
Import socket
Socket.socket(AddressFamily, Type)
说明函数socket.socket创建一个socket,该函数带有两个参数:
- AddressFamily : 可以选择AF_INET(用于Internet进程间的通信) 或者 AF_UNIX(用于同一台机器进程间通信)
- Type: 套接字类型,可以是SOCKET_STREAM(流失套接字, 主要用于TCP协议) 或者 SOCKET_DGRAM(数据报套接字, 主要用于UDP协议)
发送套接字:
import socket def main(): # 创建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 从键盘获取数据 send_data = input("请输入要发送的数据: ") udp_socket.sendto(send_data.encode("utf-8"), ('192.168.0.106', 8080)) # 对发送数据进行编码; udp_socket.close() if __name__ == "__main__": main()
接收套接字:
import socket def main(): # 创建udp套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定套接字bind(元组类型); ip地址一般不写, 表示本机任意一个ip udp_socket.bind(("", 8242)) while True: # 接受套接字recvfrom(最大字节数) recieve_data = udp_socket.recvfrom(2400) # receive_data的格式为(send_data,('ip-address', port)) print(recieve_data[0].decode('gbk')) # 对send_data进行解码并输出 # 关闭套接字 udp_socket.close() if __name__ == "__main__": main()
连续发送和接收套接字
import socket ip_address = input("please input the receiver's ip address:") port = int(input("please input the receiver's port:")) def send(udp_socket): # 发送套接字sendto(data.encode("utf-8/gbk"),('ip-address', port)) send_data = input("please input the message:") udp_socket.sendto(send_data.encode('gbk'), (ip_address, port)) # 编码格式gbk def recieve(udp_socket): # 接受套接字recvfrom(最大字节数) recieve_data = udp_socket.recvfrom(2400) # receive_data的格式为(send_data,('ip-address', port)) print(recieve_data[0].decode('gbk')) # 对send_data进行解码并输出 def main(): # 创建udp套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定套接字bind(元组类型); ip地址一般不写, 表示本机任意一个ip # udp_socket.bind(("", 2482)) while True: send(udp_socket) recieve(udp_socket) # 关闭套接字 udp_socket.close() if __name__ == "__main__": main()