level 1
深蓝梦境prince
楼主
页面代码:
var websocket;
var path = '@Url.Content("~/ws?order_uid=")' + pay_code;
var wsUri = "ws://" + window.location.host + path;
function init() {
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) {
alert("打开连接");
};
websocket.onclose = function (evt) {
alert("关闭连接");
};
websocket.onmessage = function (evt) {
alert("接收消息" + evt.data);
};
websocket.onerror = function (evt) {
alert("错误");
};
}
function doSend(message) {
if (websocket.readyState == 1) {
alert("连接成功-----if-----");
websocket.send(message);
setTimeout(function () {
if (websocket.readyState == 1) {
alert("无需尝试发送----if----");
return;
} else {
alert("尝试发送----if----");
doSend(message);
}
}, 1000);
} else {
alert("未连接或连接中断-----else----");
websocket.close();
init();
setTimeout(function () {
websocket.send(message);
setTimeout(function () {
if (websocket.readyState == 1) {
alert("无需尝试发送----else----");
return;
} else {
alert("尝试发送-----else-----");
doSend(message);
}
},1000);
}, 1000);
}
}
$(function () {
init();
var send_msg = "ooooooooo';
doSend(send_msg);
});
=============================================
后台接收消息处理代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EL.Weixin.Web.Common
{
public class SocketHandler
{
public const int BufferSize = 4096;
private static List<ClientInfo> clientPool = new List<ClientInfo>();
async Task EchoLoop(WebSocket socket)
{
var buffer = new byte[BufferSize];
var seg = new ArraySegment<byte>(buffer);
while (socket.State == WebSocketState.Open)
{
WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(seg, CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None);
}
else if (receiveResult.MessageType == WebSocketMessageType.Binary)
{
await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "can not accept", CancellationToken.None);
}
else
{
var receivedString = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
await SendMessage(receivedString);
}
}
}
/// <summary>
/// 遍历socket,判断socket的唯一性,以便于推送消息
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task SendMessage(string message)
{
if (!string.IsNullOrEmpty(message))
{
string[] array = message.Split('|');
if (array.Length >= 2)
{
List<ClientInfo> pool = clientPool.Where(t => t.socket.State == WebSocketState.Open && t.order_uid == array[1]).ToList();
foreach (ClientInfo cs in pool)
{
WebSocket client = cs.socket;
if (client != null && client.State == WebSocketState.Open)
{
ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
await client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
}
/// <summary>
/// 接收
/// </summary>
/// <param name="hc"></param>
/// <param name="n"></param>
/// <returns></returns>
static async Task Acceptor(HttpContext hc, Func<Task> n)
{
if (!hc.WebSockets.IsWebSocketRequest)
return;
var socket = await hc.WebSockets.AcceptWebSocketAsync();
var order_uid = hc.Request.Query["order_uid"].ToString();
ClientInfo client = new ClientInfo();
client.order_uid = order_uid;
client.socket = socket;
clientPool.Add(client);
var h = new SocketHandler();
await h.EchoLoop(socket);
}
/// <summary>
/// 使用SocketHandler的途径
/// </summary>
/// <param name="app"></param>
public static void Map(IApplicationBuilder app)
{
app.UseWebSockets();
app.Use(SocketHandler.Acceptor);
}
}
public class ClientInfo
{
public string order_uid { get; set; }
public WebSocket socket { get; set; }
}
}
=====================================
在本地调试没有问题,发布到服务器上之后,一直都是打开连接->关闭连接->尝试重新发送->关闭连接->打开连接->尝试重新发送->关闭连接->打开连接->尝试.....一直这样不断循环了![[泪]](/static/emoticons/u6cea.png)
2017年03月10日 14点03分
1
var websocket;
var path = '@Url.Content("~/ws?order_uid=")' + pay_code;
var wsUri = "ws://" + window.location.host + path;
function init() {
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) {
alert("打开连接");
};
websocket.onclose = function (evt) {
alert("关闭连接");
};
websocket.onmessage = function (evt) {
alert("接收消息" + evt.data);
};
websocket.onerror = function (evt) {
alert("错误");
};
}
function doSend(message) {
if (websocket.readyState == 1) {
alert("连接成功-----if-----");
websocket.send(message);
setTimeout(function () {
if (websocket.readyState == 1) {
alert("无需尝试发送----if----");
return;
} else {
alert("尝试发送----if----");
doSend(message);
}
}, 1000);
} else {
alert("未连接或连接中断-----else----");
websocket.close();
init();
setTimeout(function () {
websocket.send(message);
setTimeout(function () {
if (websocket.readyState == 1) {
alert("无需尝试发送----else----");
return;
} else {
alert("尝试发送-----else-----");
doSend(message);
}
},1000);
}, 1000);
}
}
$(function () {
init();
var send_msg = "ooooooooo';
doSend(send_msg);
});
=============================================
后台接收消息处理代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EL.Weixin.Web.Common
{
public class SocketHandler
{
public const int BufferSize = 4096;
private static List<ClientInfo> clientPool = new List<ClientInfo>();
async Task EchoLoop(WebSocket socket)
{
var buffer = new byte[BufferSize];
var seg = new ArraySegment<byte>(buffer);
while (socket.State == WebSocketState.Open)
{
WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(seg, CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, CancellationToken.None);
}
else if (receiveResult.MessageType == WebSocketMessageType.Binary)
{
await socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "can not accept", CancellationToken.None);
}
else
{
var receivedString = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
await SendMessage(receivedString);
}
}
}
/// <summary>
/// 遍历socket,判断socket的唯一性,以便于推送消息
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task SendMessage(string message)
{
if (!string.IsNullOrEmpty(message))
{
string[] array = message.Split('|');
if (array.Length >= 2)
{
List<ClientInfo> pool = clientPool.Where(t => t.socket.State == WebSocketState.Open && t.order_uid == array[1]).ToList();
foreach (ClientInfo cs in pool)
{
WebSocket client = cs.socket;
if (client != null && client.State == WebSocketState.Open)
{
ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
await client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
}
/// <summary>
/// 接收
/// </summary>
/// <param name="hc"></param>
/// <param name="n"></param>
/// <returns></returns>
static async Task Acceptor(HttpContext hc, Func<Task> n)
{
if (!hc.WebSockets.IsWebSocketRequest)
return;
var socket = await hc.WebSockets.AcceptWebSocketAsync();
var order_uid = hc.Request.Query["order_uid"].ToString();
ClientInfo client = new ClientInfo();
client.order_uid = order_uid;
client.socket = socket;
clientPool.Add(client);
var h = new SocketHandler();
await h.EchoLoop(socket);
}
/// <summary>
/// 使用SocketHandler的途径
/// </summary>
/// <param name="app"></param>
public static void Map(IApplicationBuilder app)
{
app.UseWebSockets();
app.Use(SocketHandler.Acceptor);
}
}
public class ClientInfo
{
public string order_uid { get; set; }
public WebSocket socket { get; set; }
}
}
=====================================
在本地调试没有问题,发布到服务器上之后,一直都是打开连接->关闭连接->尝试重新发送->关闭连接->打开连接->尝试重新发送->关闭连接->打开连接->尝试.....一直这样不断循环了