UDP socket编程 简单服务器和客户端,支持windows和linux

本文介绍了如何进行UDP socket编程,包括创建一个简单的服务器和客户端,该实现支持Windows和Linux操作系统。通过实例代码,读者可以理解如何在不同平台上建立和使用UDP通信。
摘要由CSDN通过智能技术生成

服务器:

#include <iostream>

#ifdef WIN32
#include <Windows.h>
#define socklen_t int
#else
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#define closesocket close
#endif

using namespace std;
int main(int argc, char* argv[])
{
	unsigned short port = 8080;
	if (argc > 1)
	{
		port = atoi(argv[1]);
	}
	//win中的初始化
#ifdef WIN32
	WSADATA ws;
	WSAStartup(MAKEWORD(2, 2), &ws);
#endif
	//创建UDP类型的socket
	int sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock <= 0)
	{
		cout << "create udp socket failed" << endl;
		return -1;
	}
	cout <<"sock:"<<sock << endl;

	//绑定端口
	sockaddr_in saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(port);
	saddr.sin_addr.s_addr = htonl(0);

	if (::bind(sock, (sockaddr*)&saddr, sizeof(saddr)) != 0)
	{
		cout << "bind port failed" << endl;
		return -2;
	}
	cout << "bind port "<<port<<" success" << endl;

	//监听
	listen(sock, 10);

	//接收
	sockaddr_in cli_saddr;
	socklen_t len = sizeof(cli_saddr);
	char* buf = new char[10240];
	int re = recvfrom(sock, buf, sizeof(buf), 0, (sockaddr*)&cli_saddr,&len);
	if (re < 0)
	{
		cout << "recvfrom failed" << endl;
		return -3;
	}
	buf[re] = '\0';
	cout << buf << endl;
	//打印ip和端口信息
	cout << "recv:" << inet_ntoa(cli_saddr.sin_addr) << ntohs(cli_saddr.sin_port) << endl;
	//回复
	sendto(sock, "67890", 6,0, (sockaddr*)&cli_saddr, sizeof(cli_saddr));
	
	closesocket(sock);
	delete[] buf;
	system("pause");
	return 0;
}

客户端:

#include <iostream>

#ifdef WIN32
#include <Windows.h>
#else
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>

#define closesocket close
#endif

using namespace std;

int main(int argc, char* argv[])
{
	unsigned short port = 8080;
	if (argc > 1)
	{
		port = atoi(argv[1]);
	}
#ifdef WIN32
	//win中的初始化
	WSADATA ws;
	WSAStartup(MAKEWORD(2, 2), &ws);
#endif
	//创建UDP类型的socket
	int sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock <= 0)
	{
		cout << "create udp socket failed" << endl;
		return -1;
	}
	cout << "create udp client socket success" << endl;

	//发送
	sockaddr_in saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(port);
	saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

	int len = sendto(sock, "12345", 6, 0, (sockaddr*)&saddr, sizeof(saddr));
	cout << "sento size is " << len << endl;

	//接收
	char* recvbuf = new char[1024];
	recvfrom(sock,recvbuf,sizeof(recvbuf),0,0,0 );
	cout << recvbuf << endl;

	//
	closesocket(sock);
	delete[] recvbuf;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值