一、 服务端构建步骤
1.初始化套接字环境WSAStartup 2.初始化地址和端口 3.创建UDP套接字socket 4.绑定端口bind 5.用recvfrom接收数据 6.用sendto发送数据 7.退出或者返回5步骤继续
二、客户端构建步骤
1.初始化套接字环境WSAStartup 2.初始化地址和端口 3.创建UDP套接字socket 4.用sendto发送数据 5.用recvfrom接收数据
三、示例代码 Sever:
代码语言:javascript复制#include <winsock.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
printf("server:n");
//1、初始化套接字环境WSAStartup
WSADATA wsadata;
int nError = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (nError != 0)
{
printf("初始化 ERRORn");
return -1;
}
//2、初始化地址和端口
unsigned short CPORT = 6556;
SOCKADDR_IN serverAddr, clientAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(CPORT);//端口
serverAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//IP
//3、创建UDP套接字socket
SOCKET server = socket(AF_INET, SOCK_DGRAM, 0);//make a socket
if (server == INVALID_SOCKET)
{
printf("create socket failed!n");
closesocket(server);
WSACleanup();
return -1;
}
//4、绑定端口bind
int retVal = bind(server, (sockaddr*)(&serverAddr), sizeof(serverAddr));//bind socket to address
if (retVal == SOCKET_ERROR)
{
printf("bind failed!n");
closesocket(server);
WSACleanup();
return -1;
}
//5、用recvfrom接收数据
int len = sizeof(clientAddr);
while (1)
{
char buf[256] = {};
int r = recvfrom(server, buf, 256, 0, (sockaddr*)&clientAddr, &len);
if (r == SOCKET_ERROR)
{
printf("server 接收数据出错n");
}
UINT uip = clientAddr.sin_addr.S_un.S_addr;
printf("%s 来自于IP:%d.%d.%d,%d n", buf, LOBYTE(uip), HIBYTE(uip), LOBYTE(HIWORD(uip)), HIBYTE(HIWORD(uip)));
//6、用sendto发送数据
char sbuf[256] = {};
cin.getline(sbuf, 256);
sendto(server, sbuf, 256, 0, (sockaddr*)&clientAddr, len);
//7、退出或者返回第5步继续
}
getchar();
getchar();
return 0;
}
Client:
代码语言:javascript复制#include <winsock.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
printf("client:n");
//1、初始化套接字环境WSAStartup
WSADATA wsadata;
int nError = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (nError != 0)
{
printf("初始化 ERRORn");
return -1;
}
//2、初始化地址和端口
unsigned short CPORT = 6556;
SOCKADDR_IN serverAddr, clientAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(CPORT);//端口
serverAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//IP
//3、创建UDP套接字socket
SOCKET client = socket(AF_INET, SOCK_DGRAM, 0);//make a socket
if (client == INVALID_SOCKET)
{
printf("create socket failed!n");
closesocket(client);
WSACleanup();
return -1;
}
//6、用sendto发送数据
while (1)
{
char sbuf[256] = {};
cin.getline(sbuf, 256);
sendto(client, sbuf, 256, 0, (sockaddr*)&serverAddr, sizeof(serverAddr));
//5、用recvfrom接收数据
int len = sizeof(clientAddr);
char buf[256] = {};
int r = recvfrom(client, buf, 256, 0, (sockaddr*)&clientAddr, &len);
if (r == SOCKET_ERROR)
{
printf("client 接收数据出错n");
}
UINT uip = clientAddr.sin_addr.S_un.S_addr;
printf("%s 来自于IP:%d.%d.%d,%d n", buf, LOBYTE(uip), HIBYTE(uip), LOBYTE(HIWORD(uip)), HIBYTE(HIWORD(uip)));
//7、退出或者返回第5步继续
}
getchar();
getchar();
return 0;
}