【发布时间】:2022-08-13 23:41:26
【问题描述】:
我想从浏览器向我的 .NET 应用程序发送一条消息,我听说了 System::Net::Sockets::TcpListener 并发现它对这项工作很感兴趣。
我有一个CLR Console App(.NET Framework 4.8)。
这是我在 TCPlistener.cpp 文件中使用System::Net::Sockets::TcpListener 的方式:
#include \"pch.h\"
using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
int main(array<System::String^>^ args)
{
TcpListener^ tcpListener = nullptr;
TcpClient^ tcpClient = nullptr;
NetworkStream^ stream = nullptr;
try {
IPAddress^ ipAddress = Dns::GetHostEntry(\"localhost\")->AddressList[0];
tcpListener = gcnew TcpListener(ipAddress, 7651);
tcpListener->Start();
Console::WriteLine(\"Waiting for a connection...\");
tcpClient = tcpListener->AcceptTcpClient();
Console::WriteLine(\"Connected!\");
array<Byte>^ bytes = gcnew array<Byte>(256);
System::String^ data = nullptr;
stream = tcpClient->GetStream();
int i;
while ((i = stream->Read(bytes, 0, bytes->Length)) != 0) {
data = System::Text::Encoding::UTF8->GetString(bytes, 0, i);
Console::WriteLine(\"Received: {0}\", data);
}
}
catch (SocketException^ exception) {
Console::WriteLine(exception);
}
finally {
if (tcpClient != nullptr) {
tcpClient->Close();
}
if (stream != nullptr) {
stream->Close();
}
if (tcpListener != nullptr) {
tcpListener->Stop();
}
}
return 0;
}
这是我的带有 javascript 的 html:
<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta charset=\"utf-8\" />
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />
<script>
function postMessage() {
const socket = new WebSocket(\'ws://localhost:7651\');
socket.addEventListener(\'open\', (event) => {
socket.send(\'Hello World!\');
});
}
</script>
</head>
<body>
<button onclick=\"postMessage()\">Post Message</button>
</body>
</html>
这是单击按钮时的输出:
Waiting for a connection...
Connected!
Received: GET / HTTP/1.1
Host: localhost:7651
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47
Upgrade
Received: : websocket
Origin: null
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt;q=0.8
Sec-WebSocket-Key: xtmy+Ue3tc48BKn37QLozA==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
为什么输出中没有\"Hello World!\"?看起来socket.send(\'Hello World!\') 不起作用,或者我没有从我的 TCPlistener.cpp 文件中正确读取它。
标签: .net c++-cli tcplistener