最近在学Windows网络编程,正好在做UDPsocket的程序,贴上来:
服务器框架函数:
socket(); bind(); recfrom(); sendto(); closesocket();
客户机框架函数:
socket(); recfrom(); sendto(); closesocket();
二、具体代码如下所示,欢迎大家一起交流
首先要打开服务器进行监听,所以服务器server代码如下:
// udpse.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#pragma comment(lib,"WS2_32.lib")
#include <iostream>
int main(int argc, char* argv[])
{
WSADATA wsaData;
//初始化socket
WSAStartup(MAKEWORD(2,2),&wsaData);
//创建socket
SOCKET recvSocket;
recvSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//将socket进行绑定
sockaddr_in reAddr;
reAddr.sin_family=AF_INET;
reAddr.sin_port=htons(5678);
reAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
bind(recvSocket,(sockaddr *)&reAddr,sizeof(reAddr));
//调用recvfrom函数绑定在socket接收到客户机数据
//获取当前系统时间 sDataTime,
SYSTEMTIME st;
GetLocalTime(&st);
//char sDataTime[30];
printf("当前系统服务器时间:%4d-%2d-%2d %2d:%2d:%2d\n",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
char recvBuf[1024];
int bufLen=1024;
//两个暂时没用的,客户机属性
sockaddr_in FromclientAddr;
int FromclientSize=sizeof(FromclientAddr);
int lbuf=recvfrom(recvSocket,recvBuf,bufLen,0,(SOCKADDR *)&FromclientAddr,&FromclientSize);
recvBuf[lbuf]=‘\0‘;
printf("客户机IP地址是:%s,端口是:%d\n,发来的数据内容是:%s\n",inet_ntoa(FromclientAddr.sin_addr),FromclientAddr.sin_port,recvBuf);
printf("接收完成,关闭socket\n");
closesocket(recvSocket);
//释放资源并退出
WSACleanup();
return 0;
}
三,客户机发送数据,代码如下:
// udp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <winsock2.h>
#pragma comment(lib,"WS2_32.lib")
int main(int argc, char* argv[])
{
WSADATA wsaData;
//初始化socket
WSAStartup(MAKEWORD(2,2),&wsaData);
//套接字初始化
SOCKET sendSocket;
sendSocket=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//设置即将连服务器地址
sockaddr_in seAddr;
seAddr.sin_family=AF_INET;
seAddr.sin_port=htons(5678);
seAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");//;htonl(INADDR_ANY)
//初始化
char sendBuf[1024]="hello wang shu qing";
int bufLen=1024;
//向服务器发送数据
printf("请输入发送数据给服务器:\n");
scanf("%s",sendBuf);
bufLen=strlen(sendBuf);
//绑定
sendto(sendSocket,sendBuf,bufLen,0,(SOCKADDR *)&seAddr,sizeof(seAddr));
//发送完成,关闭socket
printf("发送完成,关闭socket\n");
closesocket(sendSocket);
//释放资源并退出
WSACleanup();
return 0;
}
四,效果图: