程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> udp socket客戶端和udp辦事端法式示例分享

udp socket客戶端和udp辦事端法式示例分享

編輯:關於C++

udp socket客戶端和udp辦事端法式示例分享。本站提示廣大學習愛好者:(udp socket客戶端和udp辦事端法式示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是udp socket客戶端和udp辦事端法式示例分享正文


Udp Socket


#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
// initial socket library
WORD wVerisonRequested;
WSADATA wsaData;
int err;
wVerisonRequested = MAKEWORD(1, 1);
err = WSAStartup(wVerisonRequested, &wsaData);
if (err != 0)
{
return -1;
}
//if (LOBYTE(wsaData.wVersion) != 1 ||
//HIBYTE(wsaData.wHighVersion) != 1)
//{
//WSACleanup();
//return -1;
//}

// create socket
SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, 0);

// bind socket
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
bind(sockServer, (SOCKADDR *)&addrServer, sizeof(addrServer));

// receive
SOCKADDR_IN addrClient;
int len = sizeof(addrClient);
char recvBuf[100];
recvfrom(sockServer, recvBuf, 100, 0, (SOCKADDR *)&addrClient, &len);
printf("%s", recvBuf);

// close socket
closesocket(sockServer);
WSACleanup();
}

Udp Client


#include <WinSock2.h>
#include <stdio.h>

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

int main()
{
// initial socket library
WORD wVerisonRequested;
WSADATA wsaData;
int err;
wVerisonRequested = MAKEWORD(1, 1);
err = WSAStartup(wVerisonRequested, &wsaData);
if (err != 0)
{
return -1;
}
//if (LOBYTE(wsaData.wVersion) != 1 ||
//HIBYTE(wsaData.wHighVersion) != 1)
//{
//WSACleanup();
//return -1;
//}

// create socket
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);

// send
char sendBuf[100] = "this is lisi\n";
sendto(sockClient, sendBuf, strlen(sendBuf)+1,0, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));

// close connection socket
closesocket(sockClient);

// clean socket library
WSACleanup();
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved