C#后台代码
[HttpPost]
public async Task getData (string id, string patientid)
{
Rootobject entity = new Rootobject();
try
{
using (ClientWebSocket socket = new ClientWebSocket())
{
Uri uri = new Uri("ws://127.0.0.1:8080"); // 替换为实际的 WebSocket 地址
await socket.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine("Connected to WebSocket");
byte[] buffer = new byte[1024];
WebSocketReceiveResult result;
do
{
//接收连接的套接字发出的数据
result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
string message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine("Received: " + message);
}
} while (!result.CloseStatus.HasValue);
await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
Console.WriteLine("WebSocket closed");
}
}
catch (Exception ex)
{
}
}
JS方法接收数据
- web页面
<label id="address">服务端地址:</label>
<input name="" id="IpAddress" value="ws://127.0.0.1:8080" />
<button type="submit" onclick="Connect();">连接</button><br />
<label id="a">Token</label>
<input name="" id="ValueA" value="544ea9c2-de42-448e-a818-f4f7ecb7bb1c" />
<button type="submit" onclick="SendData();">提交</button><br />
<label id="b">accessToken</label>
<input name="" id="ValueB" value="544ea9c2-de42-448e-a818-f4f7ecb7bb1c" />
<div id="txtInfo" style="border: dashed 1px black;margin-top: 10px;"></div>
<div id="main" style="height:300px;"></div>
<script type="text/javascript">
var test = function () {
var print = document.getElementById('txtInfo');
var form = document.getElementById('Form');
var inputStrA = document.getElementById('ValueA');
var ipaddress = document.getElementById('IpAddress').value;
print.innerHTML += "connecting to server ..<br/>";
var url = ipaddress + "?access_token" + document.getElementById('ValueA').value;
window.ws = new WebSocket(url); //连接服务
//监听消息状态
ws.onmessage = function (msg) {
//var jsobj = JSON.parse(msg.data);//json字符串转为对象
print.innerHTML = msg.data + '<br/>'
}
//监听链接状态
ws.onopen = function () {
print.innerHTML += 'connection open <br/>'
}
//监听关闭状态
ws.onclose = function () {
print.innerHTML += 'connection closed<br/>';
}
//向服务器端发送消息
addEventListener('Connect', function (e) {
e.preventDefault();
})
}
window.onload = test();
function Connect() {
test();
}
</script>