当前位置: 首页>>代码示例>>C++>>正文


C++ StreamSocket::Bind方法代码示例

本文整理汇总了C++中StreamSocket::Bind方法的典型用法代码示例。如果您正苦于以下问题:C++ StreamSocket::Bind方法的具体用法?C++ StreamSocket::Bind怎么用?C++ StreamSocket::Bind使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在StreamSocket的用法示例。


在下文中一共展示了StreamSocket::Bind方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: SimpleStreamEchoServer_ImplementedWithSocket

	void SimpleStreamEchoServer_ImplementedWithSocket(unsigned short port)
	{
		if (InitWinSock())
		{
			return;
		}

		std::cout << "Hello World!" << std::endl;
		
		PackageFactory::getInstance().registerPackage(0, []() { return new PackableClass; });

		SocketAddress bindAddress = SocketAddressFactory::Create("0.0.0.0", port);
		StreamSocket socket;
		if (!socket.Init(bindAddress->GetFamily()))
		{
			std::cout << "Error initializing socket" << std::endl;
			socket.Close();
			ShutdownWinSock();
			return;
		}

		if (!socket.Bind(bindAddress))
		{
			std::cout << "Error binding socket" << std::endl;
			socket.Close();
			ShutdownWinSock();
			return;
		}

		if (!socket.Listen())
		{
			std::cout << "Error listening on socket" << std::endl;
			socket.Close();
			ShutdownWinSock();
			return;
		}

		std::cout << "Waiting to accept a client" << std::endl;

		StreamConnection client;
		client = socket.Accept();
		if (!client.IsConnected())
		{
			std::cout << "Error accepting client" << std::endl;
			socket.Close();
			ShutdownWinSock();
			return;
		}
		//No longer need server socket
		socket.Close();

		std::cout << "Client connected: " << client.GetSocket().GetSocket() << std::endl;

		int result = 0;
		do
		{
			auto package = client.RecvAll();
			if (package->getId() >= 0)
			{
				std::cout << "Bytes received: " << result << std::endl;

				auto person = dynamic_cast<PackableClass*>(package.get());
				person->print();

				result = client.SendAll(*person);
				if (result == SOCKET_ERROR)
				{
					std::cout << "Send failed with error: " << WSAGetLastError() << std::endl;
				}
				else
				{
					std::cout << "Bytes send: " << result << std::endl;
				}
			}
			else
			{
				auto errorPackage = dynamic_cast<ErrorPackage*>(package.get());
				std::cout << "Recv failed with error: " << errorPackage->getErrorCode() << std::endl;
				std::cout << "StreamConnection closing..." << std::endl;
				client.Disconnect();
			}

		} while (result > 0);

		client.Disconnect();
		ShutdownWinSock();
	}
开发者ID:Noise-filter,项目名称:Noise-network,代码行数:87,代码来源:SimpleStreamEchoServer_ImplementedWithSocket.cpp


注:本文中的StreamSocket::Bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。