ä¸ãTCPä¸UDPçåºå«
åºäºè¿æ¥ä¸æ è¿æ¥
ãã对系ç»èµæºçè¦æ±ï¼TCPè¾å¤ï¼UDPå°ï¼
ããUDPç¨åºç»æè¾ç®å
ããæµæ¨¡å¼ä¸æ°æ®æ¥æ¨¡å¼
ããTCPä¿è¯æ°æ®æ£ç¡®æ§ï¼UDPå¯è½ä¸¢å
ããTCPä¿è¯æ°æ®é¡ºåºï¼UDPä¸ä¿è¯
ããé¨å满足以ä¸å ç¹è¦æ±æ¶ï¼åºè¯¥éç¨UDP é¢åæ°æ®æ¥æ¹å¼ ç½ç»æ°æ®å¤§å¤ä¸ºçæ¶æ¯
ããæ¥æ大éClient
ãã对æ°æ®å®å
¨æ§æ ç¹æ®è¦æ±
ããç½ç»è´æ
é常éï¼ä½å¯¹ååºé度è¦æ±é«
ããå
·ä½ç¼ç¨æ¶çåºå« socket()çåæ°ä¸å
ããUDP Serverä¸éè¦è°ç¨listenåaccept
ããUDPæ¶åæ°æ®ç¨sendto/recvfromå½æ°
ããTCPï¼å°åä¿¡æ¯å¨connect/acceptæ¶ç¡®å®
ããUDPï¼å¨sendto/recvfromå½æ°ä¸æ¯æ¬¡å éæå®å°åä¿¡æ¯
ããUDPï¼shutdownå½æ°æ æ
äºãman----socket
ããããéè¿æ¥çsocketçmanæåå¯ä»¥çå°socketå½æ°ç第ä¸ä¸ªåæ°çå¼å¯ä»¥ä¸ºä¸é¢è¿äºå¼ï¼
ããName Purpose
ããPF_UNIX, PF_LOCAL Local communication
ããPF_INET IPv4 Internet protocols
ããPF_INET6 IPv6 Internet protocols
ããPF_IPX IPX - Novell protocols
ããPF_NETLINK Kernel user interface device
ããPF_X25 ITU-T X.25 / ISO-8208 protocol
ããPF_AX25 Amateur radio AX.25 protocol
ããPF_ATMPVC Access to raw ATM PVCs
ããPF_APPLETALK Appletalk
ããPF_PACKET Low level packet interface
ä¸ãç¼ç¨åºå«
é常æ们å¨è¯´å°ç½ç»ç¼ç¨æ¶é»è®¤æ¯æTCPç¼ç¨ï¼å³ç¨åé¢æå°çsocketå½æ°å建ä¸ä¸ªsocketç¨äºTCPé讯ï¼å½æ°åæ°æ们é常填为SOCK_STREAMãå³socket(PF_INET, SOCK_STREAM, 0)ï¼è¿è¡¨ç¤ºå»ºç«ä¸ä¸ªsocketç¨äºæµå¼ç½ç»é讯ã
ã SOCK_STREAMè¿ç§çç¹ç¹æ¯é¢åè¿æ¥çï¼å³æ¯æ¬¡æ¶åæ°æ®ä¹åå¿
é¡»éè¿connect建ç«è¿æ¥ï¼ä¹æ¯ååçï¼å³ä»»ä½ä¸æ¹é½å¯ä»¥æ¶åæ°æ®ï¼åè®®æ¬èº«æä¾äºä¸äºä¿éæºå¶ä¿è¯å®æ¯å¯é çãæåºçï¼å³æ¯ä¸ªå
æç
§åéç顺åºå°è¾¾æ¥æ¶æ¹ã
ããèSOCK_DGRAMè¿ç§æ¯User Datagram Protocolåè®®çç½ç»é讯ï¼å®æ¯æ è¿æ¥çï¼ä¸å¯é çï¼å 为é讯åæ¹åéæ°æ®åä¸ç¥é对æ¹æ¯å¦å·²ç»æ¶å°æ°æ®ï¼æ¯å¦æ£å¸¸æ¶å°æ°æ®ãä»»ä½ä¸æ¹å»ºç«ä¸ä¸ªsocket以åå°±å¯ä»¥ç¨sendtoåéæ°æ®ï¼ä¹å¯ä»¥ç¨recvfromæ¥æ¶æ°æ®ãæ ¹æ¬ä¸å
³å¿å¯¹æ¹æ¯å¦åå¨ï¼æ¯å¦åéäºæ°æ®ãå®çç¹ç¹æ¯é讯é度æ¯è¾å¿«ã大家é½ç¥éTCPæ¯è¦ç»è¿ä¸æ¬¡æ¡æçï¼èUDP没æã
ããåºäºä¸è¿°ä¸åï¼UDPåTCPç¼ç¨æ¥éª¤ä¹æäºä¸åï¼å¦ä¸ï¼
ããTCPç¼ç¨çæå¡å¨ç«¯ä¸è¬æ¥éª¤æ¯ï¼
ãã1ãå建ä¸ä¸ªsocketï¼ç¨å½æ°socket()ï¼
ãã2ã设置socketå±æ§ï¼ç¨å½æ°setsockopt(); * å¯é
ãã3ãç»å®IPå°åã端å£çä¿¡æ¯å°socketä¸ï¼ç¨å½æ°bind();
ãã4ãå¼å¯çå¬ï¼ç¨å½æ°listen()ï¼
ãã5ãæ¥æ¶å®¢æ·ç«¯ä¸æ¥çè¿æ¥ï¼ç¨å½æ°accept()ï¼
ãã6ãæ¶åæ°æ®ï¼ç¨å½æ°send()årecv()ï¼æè
read()åwrite();
ãã7ãå
³éç½ç»è¿æ¥ï¼
ãã8ãå
³éçå¬ï¼
ããTCPç¼ç¨ç客æ·ç«¯ä¸è¬æ¥éª¤æ¯ï¼
ãã1ãå建ä¸ä¸ªsocketï¼ç¨å½æ°socket()ï¼
ãã2ã设置socketå±æ§ï¼ç¨å½æ°setsockopt();* å¯é
ãã3ãç»å®IPå°åã端å£çä¿¡æ¯å°socketä¸ï¼ç¨å½æ°bind();* å¯é
ãã4ã设置è¦è¿æ¥ç对æ¹çIPå°åå端å£çå±æ§ï¼
ãã5ãè¿æ¥æå¡å¨ï¼ç¨å½æ°connect()ï¼
ãã6ãæ¶åæ°æ®ï¼ç¨å½æ°send()årecv()ï¼æè
read()åwrite();
ãã7ãå
³éç½ç»è¿æ¥ï¼
ããä¸ä¹å¯¹åºçUDPç¼ç¨æ¥éª¤è¦ç®å许å¤ï¼åå«å¦ä¸ï¼
ããUDPç¼ç¨çæå¡å¨ç«¯ä¸è¬æ¥éª¤æ¯ï¼
ãã1ãå建ä¸ä¸ªsocketï¼ç¨å½æ°socket()ï¼
ãã2ã设置socketå±æ§ï¼ç¨å½æ°setsockopt();* å¯é
ãã3ãç»å®IPå°åã端å£çä¿¡æ¯å°socketä¸ï¼ç¨å½æ°bind();
ãã4ã循ç¯æ¥æ¶æ°æ®ï¼ç¨å½æ°recvfrom();
ãã5ãå
³éç½ç»è¿æ¥ï¼
ããUDPç¼ç¨ç客æ·ç«¯ä¸è¬æ¥éª¤æ¯ï¼
ãã1ãå建ä¸ä¸ªsocketï¼ç¨å½æ°socket()ï¼
ãã2ã设置socketå±æ§ï¼ç¨å½æ°setsockopt();* å¯é
ãã3ãç»å®IPå°åã端å£çä¿¡æ¯å°socketä¸ï¼ç¨å½æ°bind();* å¯é
ãã4ã设置对æ¹çIPå°åå端å£çå±æ§;
ãã5ãåéæ°æ®ï¼ç¨å½æ°sendto();
ãã6ãå
³éç½ç»è¿æ¥ï¼
温馨提示:内容为网友见解,仅供参考