我正在创建一个简单的UWP控制台服务器应用程序,并参考this和this链接的内容。
但是,如果我根据示例创建代码并运行它,我将无法连接到服务器。此外,使用" netstat -na"等命令检查时,端口未打开。
有谁知道如何解决它?
代码如下所示。如果您在下面的代码中发现任何错误,我将不胜感激。
#include "pch.h"
#include <sstream>
#include <iostream>
using namespace Platform;
using namespace Concurrency;
using namespace Windows::Foundation;
using namespace Windows::Networking;
using namespace Windows::Networking::Sockets;
using namespace Windows::Networking::Connectivity;
using namespace Windows::Storage::Streams;
namespace SocketTest {
public ref class Server sealed {
public:
Server();
void Run();
protected:
void Server::onConnReceived(
Windows::Networking::Sockets::StreamSocketListener^ listener,
Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^ object);
};
}
using namespace SocketTest;
Server::Server() {
}
void Server::onConnReceived(
StreamSocketListener^ listener,
StreamSocketListenerConnectionReceivedEventArgs^ object)
{
try {
DataReader^ reader = ref new DataReader(object->Socket->InputStream);
//ReceiveStringLoop(reader, object->Socket);
delete object->Socket;
}
catch (Exception^ exception) {
std::cout << "onconnection error" << std::endl;
}
}
void Server::Run() {
StreamSocketListener^ listener = ref new StreamSocketListener();
listener->ConnectionReceived += ref new TypedEventHandler<Windows::Networking::Sockets::StreamSocketListener^, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^>(this, &Server::onConnReceived);
listener->Control->KeepAlive = true;
create_task(listener->BindServiceNameAsync(L"12345")).then(
[=]
{
try
{
std::cout << "Listening ..." << std::endl;
}
catch (Exception^ exception)
{
std::cout << "Bind error" << exception->Message->Data() << std::endl;
}
});
}
int main(Platform::Array<Platform::String^>^ args)
{
Server^ s = ref new Server();
s->Run();
getchar();
}
或者,如果您有更好的代码示例,请告诉我。