面向无连接的UDP网路编程与TCP相比不用listen监听,不需要accp接受客户端请求
(1)服务器端程序
#include<WinSock2.h>
#include<stdio.h>
///
//客户端程序,向服务器端发送请求//
/
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested,&wsaData);
if(err!=0)
{
return;
}
if(LOBYTE(wsaData.wVersion)!=1||HIBYTE(wsaData.wVersion)!=1)
{
WSACleanup();
return;
}
//以上部分是初始化部分,打开SOCKET库
SOCKET socketClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);//设置要请求的服务器的地址及端口号
connect(socketClient,(sockaddr*)&addrSrv,sizeof(SOCKADDR));//建立连接请求
char recvBuf[100];
recv(socketClient,recvBuf,100,0);//接收服务器的信息
printf("%s\n",recvBuf);
send(socketClient,"this is zhangsan",strlen("this is zhangsan")+1,0);//像服务器发送信息
closesocket(socketClient);//关闭套接字
WSACleanup();//关闭WSA
}
(2)客户端程序
#include<winsock2.h>
#include<stdio.h>
//基于UDP的面向无连接的客户端程序//
///
void main()
{
/*用WSASTARTUP来启动有关socket的动态链接库*/
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
WSACleanup( );
return;
}
SOCKET sockClient=socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);//设置要请求的服务器的 IP地址及端口信息
sendto(sockClient,"HELLO WORLD",sizeof("HELLO WORLD")+1,0,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
closesocket(sockClient);//关闭套接字
WSACleanup();//关系WSA
}
关于具体的UDP和TCP的区别读者可以结合上一篇文章自己总结