UDP實現伺服器和客戶端的通訊

2021-09-19 10:10:48 字數 1782 閱讀 2916

一 服務端

#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include char rbuf[50];  

int main()

//設定埠復用

setsockopt(sockfd,sol_socket,so_reuseaddr,&on,sizeof(on));

//繫結位址資訊,ip資訊

ret = bind(sockfd,(struct sockaddr*)&saddr,sizeof(struct sockaddr));

if(ret<0)

socklen_t val = sizeof(struct sockaddr);

//迴圈接收客戶端發來的訊息

while(1)

printf("the data :%s\n",rbuf);

bzero(rbuf,50);

} //關閉udp套接字,這裡不可達的。

close(sockfd);

return 0;

}

二 客戶端

#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include char wbuf[50];  

int main()

//設定埠復用

setsockopt(sockfd,sol_socket,so_reuseaddr,&on,sizeof(on));

//迴圈傳送資訊給服務端

while(1)

bzero(wbuf,50);

} close(sockfd);

return 0;

}

三 執行

1 先啟動服務端

[root@localhost test]# g++ test.cpp -o test

[root@localhost test]# ./test

waiting data

2 在啟動客戶端,並輸入資料

[root@localhost test]# g++ client.cpp -o client

[root@localhost test]# ./client

please enter data:

明天你來嗎?

3 服務端結果

[root@localhost test]# ./test

waiting data

the data :明天你來嗎?

waiting data

UDP 客戶端伺服器

udp 客戶端 include include include include include define size 100 define ip 127.0.0.1 define port 10086 int main struct sockaddr in addr 建立socket udp so...

Udp 模擬實現客戶端與伺服器通訊

客戶端模組 include include include std string include close介面 include atoi介面 include 位址結構定義 include 位元組序轉換介面 include 套接字介面 class udpsocket 1.建立套接字 bool soc...

伺服器和客戶端的通訊

伺服器 include include include include include include include include define port 8888 int main struct sockaddr in server addr 用於存放伺服器本身的資訊,包括自己的port和ip...