PyQt5快速开发与实战电子书pdf免费下载
½²µ½UDPºÍTCP֮ǰÔÛÃÇÏÈÁ˽âÒ»ÏÂsocket
Socket
socket¼ò³ÆÌ×½Ó×Ö£¬Êǽø³Ì¼äͨÐŵÄÒ»ÖÖ·½Ê½¡£ÓëÆäËûµÄ·½Ê½µÄ½ø³Ì¼äµÄͨѶµÄ·½Ê½²»Í¬µÄÊÇ£¬socketÊÇʵÏÖÁËÖ÷»ú¼ä½ø³Ì¼äµÄͨѶ¡£ÎÒÃÇÍøÂçÉϵĸ÷ÖÖ·þÎñ¶¼ÊÇ»ùÓÚsocketÀ´Íê³ÉµÄ¡£ÀýÈçQQ.΢ÐÅ¡£
ÔõôÑù´´½¨socketÄØ¡£
´´½¨Ò»¸ötcpsocket£º
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
´´½¨Ò»¸öUDPÀàÐ͵Äsocket;
# # ´´½¨Ì×½Ó×Ö # udpSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDP½éÉÜ
udp¡ª¨CÊý¾Ý±¨ÎÄÐÒ飬ÊÇÒ»¸öÎÞÁ¬½ÓµÄ¼òµ¥µÄÃæÏòÊý¾Ý±¨µÄÔËÊä²ãÐÒ飬UDP²»Ìṩ¿É¿¿ÐÔ£¬ËûÖ»Êǽ«Ó¦ÓóÌÐò´«Ë͸øIP²ãµÄÊý¾Ý±¨ÎÄ·¢ËͳöÈ¥£¬²¢²»±£Ö¤ÄÜ·ñ´ïµ½Ä¿µÄµØ¡£ÓÉÓÚUDPÔÚ´«ÊäµÄ¹ý³ÌÖв»ÐèÒªºÍ·þÎñÆ÷½¨Á¢Á´½Ó¡£ÇÒûÓг¬Ê±ÖØ·¢µÄµÄ»úÖÆ¡£¹Ê¶ø´«ÊäºÜ¿ì¡£
ÏÂÃæ¼òµ¥Í¨¹ýʾÒâͼÀ´Ñо¿Ò»ÏÂUDP¡£
UDP ·¢ËÍÊý¾Ý
import socket # ÉèÖÃsocket udpSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # ÉèÖÃÄ¿µÄ¶Ë¿ÚºÍIP sendArr = ('192.168.31.174',65535) sendData = input('ÇëÊäÈëÄãÒª·¢Ë͵ÄÐÅÏ¢') # ·¢ËÍÊý¾Ý,´Ë´¦ÓÐÒ»¸ö¿ÓÊÇsendto£¨£©ÀïÃæµÄ²ÎÊý±ØÐë¶þ½øÖÆÊý¾Ý£¬²»ÄÜÖ±½Ó´«×Ö·û´® udpSocket.sendto(sendData.encode('utf-8'),sendArr) udpSocket.close()
UDP ½ÓÊÕÊý¾Ý
import socket # ´´½¨UDPÌ×½Ó×Ö udpSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # °ó¶¨¶Ë¿ÚºÅ udpSocket.bind(("", 7789)) recvData = udpSocket.recvfrom(1024) content, destInfo = recvData print("content is %s"%content) print("content is %s"%content.decode("utf-8")) print(recvData) udpSocket.close()
´Ó´òÓ¡½á¹ûÎÒÃÇ¿ÉÒÔ¿´³örecvDataÖаüº¬ÊÇÒ»¸öÔª×棬Ԫ×æ½ÓÊÕµ½Êý¾Ý·½ip.ºÍ¶Ë¿ÚºÅµÄ¡£
·¢ËÍͨ¹ý¶Ë¿ÚºÅºÍIP½«Êý¾Ý·¢Ë͸ø½ÓÊÕ·½£¬½ÓÊÕ·½¼àÌý¶Ë¿Ú£¬ÕâÑù¾ÍÍê³ÉÒ»´ÎUDPͨÐŵĹý³Ì£¬Õâ¸ö¹ý³ÌÉæ¼°µ½£¬·¢ËÍ·½×é°ü£¬½ÓÊÕ½â°üµÄ¹ý³Ì¡£
转载请注明:谷谷点程序 » 对python中UDP,socket的使用详解