欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vc udp socket 例子

程序员文章站 2022-06-29 18:55:04
...
#include "stdafx.h"
#include "common.h"


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

#define SERVER_PORT 6000

WORD wVersionRequested;
WSADATA wsaData;
int err;
SOCKET sockSrv;
SOCKET sockCli;
DWORD svrTid;
DWORD cliTid;


DWORD WINAPI udpRecvThread(LPVOID lparam);

typedef void(*MsgCallBack)(u8 *pbuf, int len, SOCKADDR_IN *paddr);

typedef struct {
	MsgCallBack msgHandleFunc;
	SOCKET socket;
	char *name;
}T_ParamSock;


const char *serverName = "server";
const char *clientName = "client";



T_ParamSock svrParamSock;
T_ParamSock cliParamSock;


int initWSocket() {
	wVersionRequested = MAKEWORD(1, 1);
	err = WSAStartup(wVersionRequested, &wsaData);
	if (err != 0) {
		return -1;
	}

	if (LOBYTE(wsaData.wVersion) != 1 ||
		HIBYTE(wsaData.wVersion) != 1) {
		WSACleanup();
		return -1;
	}

}


void ServerMsgHandle(u8 *pbuf, int len, SOCKADDR_IN *pclientaddr) {
	printf("%s\n", pbuf);
	sendto(sockSrv, "world", 5, 0,(SOCKADDR *) pclientaddr, sizeof(sockaddr_in));
}

void ClientMsgHandle(u8 *pbuf, int len, SOCKADDR_IN *pclientaddr) {
	printf("%s\n", pbuf);
}


int UdpClient() {
		
	sockCli = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	sockaddr_in seAddr;
	seAddr.sin_family = AF_INET;
	seAddr.sin_port = htons(SERVER_PORT);
	seAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

	cliParamSock.msgHandleFunc = ClientMsgHandle;
	cliParamSock.socket = sockCli;
	cliParamSock.name =(char*) clientName;

	// start client thread
	CreateThread(NULL, 4096, udpRecvThread, (void*)&cliParamSock, 0, &cliTid);
	sendto(sockCli, "hello", 5, 0,(SOCKADDR *) &seAddr, sizeof(seAddr));
	return 0;

}


int UdpServer() {


	sockSrv = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	SOCKADDR_IN addrSrv;
	addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//htonl(INADDR_ANY); 
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(SERVER_PORT);
	err = bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));
	if (SOCKET_ERROR == err)
	{
		printf("bind() called failed! The error code is: %d\n", WSAGetLastError());
		return -1;
	}
	else
	{
		printf("bind() called successful!\n");
	}

	svrParamSock.msgHandleFunc = ServerMsgHandle;
	svrParamSock.socket = sockSrv;
	svrParamSock.name = (char*)serverName;
	// start server thread
	CreateThread(NULL, 4096, udpRecvThread, (void*)&svrParamSock, 0, &svrTid);
	return 0;
}




DWORD WINAPI udpRecvThread(LPVOID lparam) {
	T_ParamSock *pSockPara;

	pSockPara = (T_ParamSock *)lparam;

	while (1)
	{
		SOCKADDR_IN addrClient;
		int len = sizeof(SOCKADDR);
		char recvBuf[8192];
		int recv_len;
		recv_len = recvfrom(pSockPara->socket, recvBuf, 8192, 0, (SOCKADDR*)&addrClient, &len);
		if (recv_len > 0)
		{
			//char buffer[8192];
			recvBuf[recv_len] = 0;
			printf("%s: recv  %d \n",pSockPara->name,recv_len);
			pSockPara->msgHandleFunc((u8*)&recvBuf[0], recv_len,&addrClient);			
		}
	}


}

 

上一篇: UDP连接类

下一篇: 简单 UDP 操作类