一、函式化
1.1伺服器使用的函式
建立socket----->socket
繫結位址-------->bind
接受資料-------->recvfrom
傳送資料-------->sendto
結束連線-------->close
1.2客戶機使用函式
建立套接字------>socket
傳送資料-------->sento
接受資料-------->recvfrom
結束連線-------->close
二、函式學習
2.1 傳送資料sendto
2.1.1包含標頭檔案
#include
#include
2.1.2函式原型
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
2.1.3函式引數
sockfd:建立的套接字
len:資料長度
flags:識別符號
addrlen:位址長度
2.1.4返回值
實際傳送的資料量
2.2接收資料recvfrom
2.2.1包含標頭檔案
#include
#include
2.2.2函式原型
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
2.2.3函式引數
sockfd:建立的套接字
len:資料長度
flags:識別符號
2.2.4返回值
以位元組計數的訊息長度,若無可用訊息或對方已經按序結束則返回0,若出錯則返回-1
三、編寫伺服器**
touch udp_server.c
chmod 777 udp_server.c
1 #include 2 #include編譯執行:3 #include 4 #include in.h> 5 6 7 #define portnum 8888 8 #define msg_size 128 9 intmain() 10 36 //4.結束連線 37 close(sockfd); 38 return 0; 39 }
四、編寫客戶機**
touch udp_client,c
chmod 777 udp_client.c
#include #include #include #include in.h>編譯執行:#define buffer_size 128 #define portnum 8888 int main(int argc,char **ar**) //1.建立套接字 sockfd = socket(af_inet,sock_dgram,0); //初始化伺服器位址 bzero(&server_addr,sizeof(structsockaddr_in)); server_addr.sin_family =af_inet; server_addr.sin_port =htons(portnum); inet_aton(ar**[1],&server_addr.sin_addr); //2.傳送資料 while(1) //3.關閉連線 close(sockfd); return 0; }
4.1則可以看到伺服器執行結果
unix環境程式設計 UDP通訊
一 udp伺服器 程式設計的端一般步驟是 1 用函式socket 建立socket 第二個引數為sock dgram 2 用函式bind 繫結ip 位址 埠資訊 3 用函式recvfrom 接收資料 4 關閉網路連線 udp客戶端 程式設計的一般步驟是 1 建立乙個socket 用函式socket ...
Python 網路通訊程式設計之udp通訊程式設計
import socket 1.建立例項,即資料報套接字 server socket.socket socket.af inet,socket.sock dgram 2.繫結位址,進行監聽 server.bind 127.0.0.1 3120 3.收發訊息 while true data serve...
python網路程式設計 之udp通訊
encoding utf 8 ss socket 建立乙個伺服器套接字 ss.bind 繫結伺服器套接字 inf loop 伺服器無限迴圈 cs ss.recvfrom ss.sendto 對話 接收與傳送 ss.close 關閉伺服器套接字 建立乙個能接收客戶的訊息,在訊息前加乙個時間戳後返回的 ...