windows开发环境下C++编写UDP传送字符串消息

身边一非码农同事要实现这个功能,我从github上引用相关源码简单封装了一下,留帖以备后用。

应为写在一个函数里面,所以mode用来区分S和C,服务器端调用该函数需要新启用一个线程。

这个头文件,环境为VS,控制台程序即可。

#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include 
#include 
#include 
#include 
#pragma comment(lib, "ws2_32.lib")

using namespace std;

int cal(int mode/*0-server, 1-client*/,string ipAndPort/*server: port, client: ip:port */, string msg="") {
	// parse mode and from argv
	int error = 0;//syntax error
	//parse ipaddr and port from argv
	char* port = NULL;
	unsigned long ipaddr = INADDR_ANY;
	if (mode) {
		ipaddr = inet_addr(strtok_s((char*)(ipAndPort.c_str()), ":", &port));
	}
	else {
		port = (char*)(ipAndPort.c_str());
	}
	//init socket
	WSADATA wsaData;
	WORD socketVersion = MAKEWORD(2, 2);
	if (WSAStartup(socketVersion, &wsaData) != 0)
	{
		printf("socket error occured");
		return -1;
	}
	SOCKET msocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	sockaddr_in msocktaddr;
	msocktaddr.sin_family = AF_INET;
	msocktaddr.sin_port = htons(atoi(port));
	msocktaddr.sin_addr.S_un.S_addr = ipaddr;

	// send or receive
	if (mode) {// client send msg
		sendto(msocket, msg.c_str(), strlen(msg.c_str()), 0, (sockaddr *)&msocktaddr, sizeof(msocktaddr));

	}else {//server receive
		if (bind(msocket, (sockaddr *)&msocktaddr, sizeof(msocktaddr)) == SOCKET_ERROR) {
			printf("socket bind error !");
			closesocket(msocket);
			return -1;
		}
		printf("Server IP Address (port %s):\r\n", port);
		system("@echo off & for /f \"tokens=2 delims=:\" %i in ('ipconfig ^| find /i \"IPv4\"') do (echo %i) ");
		printf("----------------\r\n");

		//init
		time_t now;
		struct tm tmTmp;
		char buffer[10];
		sockaddr_in msocktaddr_remote;
		int maddrlen_remote = sizeof(msocktaddr_remote);
		int num = 0;
		char recvdata[255];
		int ret;
		string cmd, arg;//for /ca

		while (1){
			ret = recvfrom(msocket, recvdata, 255, 0, (sockaddr *)&msocktaddr_remote, &maddrlen_remote);
			if (ret > 0){
				time(&now);
				localtime_s(&tmTmp, &now);
				strftime(buffer, 10, "%H:%M:%S", &tmTmp);
				num++;
				recvdata[ret] = 0x00;
				printf("[%03d] %s\t%s\n", num, buffer, recvdata);
				//send back
				char * sendData = "Received\n";
				sendto(msocket, sendData, strlen(sendData), 0, (sockaddr *)&msocktaddr_remote, maddrlen_remote);
			}
		}
		closesocket(msocket);
		WSACleanup();
		return 0;
	}
}

int main()
{
	cal(0,"5000");
	//cal(1, "127.0.0.1:5000","honey");
	//cal(1, "127.0.0.1:5000", "i want you");
    return 0;
}

你可能感兴趣的:(C++,C#)