vc 基於UDP的對話程式

2021-06-10 09:18:29 字數 1594 閱讀 4767

伺服器:

#include #include int main()		

if ( lobyte( wsadata.wversion ) != 1 ||

hibyte( wsadata.wversion ) != 1 )

socket srvier = socket(af_inet, sock_dgram, 0);

sockaddr_in addr_srv;

addr_srv.sin_family = af_inet;

addr_srv.sin_port = htons(6000);

addr_srv.sin_addr.s_un.s_addr = htonl(inaddr_any);

bind(srvier, (sockaddr *)&addr_srv, sizeof(addr_srv));

char rbuf[100];

char sbuf[100];

char tbuf[100];

sockaddr_in addr_cli;

int len = sizeof(addr_cli);

while (1)

sprintf(tbuf, "%s say : %s", inet_ntoa(addr_cli.sin_addr), rbuf);

printf("%s\n", tbuf);

printf("please input data:");

gets(sbuf);

sendto(srvier, sbuf, strlen(sbuf)+1, 0, (sockaddr *)&addr_cli, len); }

closesocket(srvier);

wsacleanup();

return 0;

}

客戶端:

#include #include int main()		

if ( lobyte( wsadata.wversion ) != 1 ||

hibyte( wsadata.wversion ) != 1 )

socket client = socket(af_inet, sock_dgram, 0);

sockaddr_in addr_srv;

addr_srv.sin_family = af_inet;

addr_srv.sin_port = htons(6000);

addr_srv.sin_addr.s_un.s_addr = inet_addr("127.0.0.1");

int len = sizeof(addr_srv);

char sbuf[100];

char rbuf[100];

char tbuf[100];

while (1)

sprintf(tbuf, "%s say: %s", inet_ntoa(addr_srv.sin_addr), rbuf);

printf("%s\n", tbuf);

} closesocket(client);

wsacleanup();

return 0;

}

時間程式(基於UDP)

server 需求 寫乙個時間同步的伺服器 服務端接收請求 按照client端傳送的時間格式,將伺服器時間轉換成對應格式 傳送給客戶端 import time import socket sk socket.socket type socket.sock dgram sk.bind 127.0.0....

基於UDP的簡單聊天程式

pragma comment lib,ws2 32.lib include include void main if lobyte wsadata.wversion 1 hibyte wsadata.wversion 1 socket socksrv socket af inet,sock dgra...

基於UDP簡單聊天程式

server.c include include include include include include include include include include define server port 8888 define max msg size 1024 void udps re...