websocket长连接

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket长连接相关的知识,希望对你有一定的参考价值。

代码如下:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace SYW_WebScoket
{
public class WebSocketManager : Singleton<WebSocketManager>
{

#region Field

public static string m_address { get; set; }

/// <summary>
/// 是否发送
/// </summary>
private bool IsSend;
/// <summary>
/// 是否接收
/// </summary>
private bool IsRecv;
/// <summary>
/// 是否关闭
/// </summary>
public bool IsClose { get; set; }
//public string ReturnedMessage { get; set; }

public string Message { get; set; }
public string Recv { get; set; }

private Queue<string> message_Queue = new Queue<string>();
private Dictionary<string, WebSocket> m_socketDict = new Dictionary<string, WebSocket>();

#endregion

/// <summary>
/// 使用协程去连接
/// </summary>
/// <param name="ws"></param>
/// <returns></returns>
IEnumerator StartConnect(string address)
{
IsSend = false;
IsRecv = false;
IsClose = false;
WebSocket ws = GetSocket(address);
yield return ws.Connect();
m_address = address;
for (int i = 0; i < ws.m_Messages.Count; i++)
{
Recv = ws.RecvString();
}
while (true)
{
if (IsSend)
{
//TODO发送信息
ws.SendString(message_Queue.Dequeue());
IsSend = false;

IsRecv = true;
}
if (IsRecv)
{
//TODO接收消息
for (int i = 0; i < ws.m_Messages.Count; i++)
{
Recv = ws.RecvString();
}

IsRecv = false;
}
if (IsClose)
{
break;
}

if (ws.error != null)
{
Debug.LogError("Error: " + ws.error);
break;
}

yield return new WaitForEndOfFrame();
}
ws.Close();

}

#region Method

/// <summary>
/// 创建一个 WebSocket
/// </summary>
/// <param name="address">地址</param>
/// <returns></returns>
private WebSocket CreateSocket(string address)
{
WebSocket ws = new WebSocket(new System.Uri(address));
m_socketDict.Add(address, ws);
return ws;
}

/// <summary>
/// 得到一个WebSocket
/// </summary>
/// <param name="address">地址</param>
/// <returns></returns>
public WebSocket GetSocket(string address)
{
if (m_socketDict.ContainsKey(address))
return m_socketDict[address];
return CreateSocket(address);
}

/// <summary>
/// 连接服务器
/// </summary>
/// <param name="address">地址address</param>
public void ConnectSocket(string address)
{
StartCoroutine(StartConnect(address));
}

/// <summary>
/// 发送消息
/// </summary>
/// <param name="message"></param>
public void Send(string message)
{
message_Queue.Enqueue(message);
IsSend = true;
}

#endregion

}
}

 

以上是关于websocket长连接的主要内容,如果未能解决你的问题,请参考以下文章

Netty中使用WebSocket实现服务端与客户端的长连接通信发送消息

python 如何建立socket长连接

Websocket长连接循环连接

WebSocket 长连接详解

Vue+WebSocket 实现页面实时刷新长连接

Spring+Stomp+ActiveMq实现websocket长连接