【发布时间】:2016-12-22 14:59:22
【问题描述】:
我正在尝试编写 C# TCP 服务器并连接我的 Web 应用程序。这是我正在关注的教程。 Link
我设法启动了服务器,但我从我的 web 应用程序收到的消息是加密的。
C# 代码段
using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Application
{
class MainClass
{
public static void Main()
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8181);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:8181.{0}Waiting for a connection...", Environment.NewLine);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
NetworkStream stream = client.GetStream();
while (true)
{
while (!stream.DataAvailable) ;
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
String data = Encoding.UTF8.GetString(bytes);
//handshaking
if (new Regex("^GET").IsMatch(data))
{
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
}
else
{
Console.WriteLine(data);
}
}
}
}
}
HTML 片段
<form>
<input id="textField1" type="text" style="margin: 0 5px; width: 200px; height: 40px;" placeholder="Enter data">
<button id="sendTextField1" type="button" class="btn btn-info">Send</button>
</form>
<script type="text/javascript">
var start = function () {
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://127.0.0.1:8181/');
ws.onmessage = function (evt) {
console.log(evt.data);
};
ws.onopen = function () {
console.log("Connected");
};
ws.onclose = function () {
console.log("Closed");
};
document.getElementById("sendTextField1").onclick = function() {
sendToSocket(document.getElementById('textField1').value);
};
function sendToSocket(value){
console.log("Sending value to socket " + value + " ");
ws.send(value);
};
}
window.onload = start;
我尝试将消息编码为另一种格式,但完全没有运气。
消息不是以原始格式发送的,但它们具有数据框架。
这与我现在遇到的问题有关吗?我是否需要找到一种方法来解构从应用中获得的数据?
【问题讨论】:
-
顺便说一句,写那篇文章的人不知道正确处理 TCP 流; bleugh -
DataAvailable上的热循环,试图解析数据包(通过DataAvailable)而不是逻辑帧......非常非常糟糕的示例代码。 -
作为记录,您链接到的示例确实显示了掩码代码(“解码算法”),但是......那里有很多令人讨厌的东西。 ..
-
while (true) { while (!stream.DataAvailable); ...让我想哭 -
哈哈大佬,我也不清楚,Mozilla官方教程,觉得对新手有用