UdpServer

2024-03-04 18:08
文章标签 udpserver

本文主要是介绍UdpServer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

// UdpServer.cpp : 定义控制台应用程序的入口点。
//



#include "stdafx.h"  
#include <iostream>  
#include <stdio.h>  
#include <WinSock2.h>  


#pragma comment(lib, "ws2_32.lib")  


using namespace std;


const int MAX_BUF_LEN = 255;


int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wasData;//指向WinSocket信息结构的指针  
int err;


wVersionRequested = MAKEWORD(2, 2);
// 初始化winsock库,使用socket的前提  
err = WSAStartup(wVersionRequested, &wasData);
if (err != 0)
{
return -1;
}
if (LOBYTE(wasData.wVersion) != 2 || HIBYTE(wasData.wVersion) != 2)
{
WSACleanup();
return -1;
}
SOCKET conn_sock = socket(AF_INET, SOCK_DGRAM, 0);
if (conn_sock == INVALID_SOCKET)
{
err = WSAGetLastError();
printf("socket error:%d\n", err);
closesocket(conn_sock);
WSACleanup();
return -1;
}
bool bOpt = true;
//打开广播选项  
setsockopt(conn_sock, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));


// 设置发往的地址  
SOCKADDR_IN saUdpServ;
memset(&saUdpServ, 0, sizeof(saUdpServ));
saUdpServ.sin_family = AF_INET;
saUdpServ.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);
saUdpServ.sin_port = htons(7001);
int nSize = sizeof(SOCKADDR_IN);


char buff[MAX_BUF_LEN];
memset(buff, 0, MAX_BUF_LEN);
int nLoop = 0;
char* ip = NULL;
while (1){
nLoop++;
sprintf(buff, "Message %d", nLoop);
int nSendSize = sendto(conn_sock, buff, strlen(buff), 0, (SOCKADDR*)&saUdpServ, nSize);
if (nSendSize == SOCKET_ERROR)
{
err = WSAGetLastError();
printf("sendto error:%d\n", err);
closesocket(conn_sock);
WSACleanup();
return -1;
}
printf("send: %s\n", buff);
Sleep(5000);
}


closesocket(conn_sock);
WSACleanup();
return 0;

}

这篇关于UdpServer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/774010

相关文章

C++之基于Winsock2封装UDPServer与UDPClient

文章目录 Socket过程UDPServer.hUDPServer.cppUDPClient.hUDPClient.cppmain.cppCMakeLists.txt测试截图 Socket过程 UDPServer UDPClient UDPServer.h #ifndef UDPSERVER_H_INCLUDED#define UDPSERVER_H_INCLU