伺服器端(server)步驟:
1、建立socket套接字(套接字型別為資料報套接字)
2、填充位址資訊
3、繫結
4、收發訊息
(5、關閉socket)
客戶端(client)步驟
1、建立socket套接字
2、填充位址資訊
3、傳送
4、接收
5、關閉socket
例:伺服器程式設計:
#include #include /* see notes */
#include #include #include #include #include #include #define server_port 8888
#define buflen 256
int setup_socket()
//2,填充位址資訊
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = af_inet;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = inaddr_any;
//設定可以復用位址
int on = 1;
if(setsockopt(sock_server, sol_socket, so_reuseaddr, &on, sizeof(on)) == -1)
//3,bind
if(bind(sock_server, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
return sock_server;
}int main()
; int ret = 0, server_sock;
struct sockaddr_in client_addr;
bzero(&client_addr, sizeof(client_addr));
socklen_t len = sizeof(client_addr);
server_sock = setup_socket();
if(server_sock < 0)
while(1)
printf("client ip:%s, port: %d\n", (char *)inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
printf("recvfrom : %s\n", buf);
//5,傳送資料
bzero(buf, sizeof(buf));
strcpy(buf, "hello world\n");
sleep(1);
if((ret = sendto(server_sock, buf, strlen(buf), 0, (const struct sockaddr * )&client_addr, len)) < 0)
}return ret;
}
客戶端程式設計:
#include #include /* see notes */
#include #include #include #include #include #include #define server_port 8888
#define client_port 6789
#define buflen 256
int main()
; struct sockaddr_in server_addr;
socklen_t socklen = sizeof(server_addr);
bzero(&server_addr, sizeof(server_addr));
//1,建立socket
int cli_sock = socket(af_inet, sock_dgram, 0);
if(cli_sock < 0)
//可選,
struct sockaddr_in cli_addr;
bzero(&cli_addr, sizeof(cli_addr));
cli_addr.sin_family = af_inet;
cli_addr.sin_port = htons(client_port);
cli_addr.sin_addr.s_addr = inaddr_any;
if(bind(cli_sock, (struct sockaddr *)&cli_addr, sizeof(cli_addr)) < 0)
//2,填寫伺服器位址資訊
server_addr.sin_family = af_inet;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
//3,傳送
strcpy(buf, "i am a client");
if((ret = sendto(cli_sock, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, socklen)) < 0)
//4,接收
bzero(buf, sizeof(buf));
if((ret = recvfrom(cli_sock, buf, buflen, 0, (struct sockaddr *)&server_addr, &socklen)) < 0)
printf("recvfrom:%s\n", buf);
sock_err:
//5,關閉socket
close(cli_sock);
}
簡易案例,只做參考。 Qt實現UDP通訊簡例
1 qt實現tcp通訊簡例 2 qt實現udp廣播簡例 qt 4 網路程式設計 4 目錄 接收端截圖 qt實現udp通訊 原版例子!singals slots 官方文件 qt入門之訊號與槽機制 qt 訊號槽的實現 qt學習 之 socket通訊 qt的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 關閉伺服器套接字 建立乙個能接收客戶的訊息,在訊息前加乙個時間戳後返回的 ...