ict.shenzhi/Assets/Scripts/UI/MainScenesUI/Chat/ChatRequest.cs

296 lines
8.8 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WebSocketSharp.Server;
using System;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
//using Codice.CM.WorkspaceServer;
public class ChatRequest : MonoBehaviour
{
public static ChatRequest instance;
public string version = "1.0";
WebSocketServer wss;
HttpListener httpobj;
[HideInInspector]
public Queue<JObject> reciveData = new Queue<JObject>();
Action<JObject> handleFun_szr = null;
Action<JObject> handleFun_jqr = null;
Action<JObject> handleFun_wrj = null;
Action<JObject> handleFun_other = null;
[HideInInspector]
public ServerHandlerUI handler = null;
private void Awake()
{
instance = this;
}
private void Start()
{
StartWebsocketServer(10088);
//StartHttpServer(10089);
}
private void OnDestroy()
{
StopWebsocketServer();
}
private void Update()
{
if (reciveData.Count > 0)
{
int count = reciveData.Count;
for (int i = 0; i < count; i++)
{
if (reciveData.TryDequeue(out JObject result))
{
if (result["type"].ToString() == "szr")
{
handleFun_szr(result);
}
else if (result["type"].ToString() == "jqr")
{
handleFun_jqr(result);
}
else if (result["type"].ToString() == "wrj")
{
handleFun_wrj(result);
}
else
{
handleFun_other(result);
}
}
}
}
}
/// <summary>
/// Æô¶¯ÏûÏ¢¼àÌý
/// </summary>
/// <param name="port"></param>
private void StartWebsocketServer(int port)
{
try
{
string text = "ws://127.0.0.1:" + port;
wss = new WebSocketServer(text);
wss.AddWebSocketService<ServerHandlerUI>("/cxx");
wss.KeepClean = false;
wss.Start();
Debug.Log("¿ªÊ¼¼àÌý");
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
}
/// <summary>
/// ¹Ø±ÕÏûÏ¢¼àÌý
/// </summary>
private void StopWebsocketServer()
{
if (wss != null)
{
wss.RemoveWebSocketService("/cxx");
wss.Stop();
wss = null;
Debug.Log("¹Ø±Õ¼àÌý");
}
}
#region http
private void StartHttpServer(int port)
{
httpobj = new HttpListener();
//¶¨Òåurl¼°¶Ë¿ÚºÅ£¬Í¨³£ÉèÖÃΪÅäÖÃÎļþ
httpobj.Prefixes.Add("http://127.0.0.1:" + port + "/cxx/");
//Æô¶¯¼àÌýÆ÷
httpobj.Start();
//Òì²½¼àÌý¿Í»§¶ËÇëÇ󣬵±¿Í»§¶ËµÄÍøÂçÇëÇóµ½À´Ê±»á×Ô¶¯Ö´ÐÐResultίÍÐ
//¸ÃίÍÐûÓзµ»ØÖµ£¬ÓÐÒ»¸öIAsyncResult½Ó¿ÚµÄ²ÎÊý£¬¿Éͨ¹ý¸Ã²ÎÊý»ñÈ¡context¶ÔÏó
httpobj.BeginGetContext(Result, null);
Debug.Log("httpserver ³õʼ»¯Íê³É");
}
private void StopHttpServer()
{
}
private void Result(IAsyncResult ar)
{
//µ±½ÓÊÕµ½ÇëÇóºó³ÌÐòÁ÷»á×ßµ½ÕâÀï
//¼ÌÐøÒì²½¼àÌý
httpobj.BeginGetContext(Result, null);
var guid = Guid.NewGuid().ToString();
Debug.Log($"½Óµ½ÐµÄÇëÇó:{guid},ʱ¼ä£º{DateTime.Now.ToString()}");
//»ñµÃcontext¶ÔÏó
var context = httpobj.EndGetContext(ar);
var request = context.Request;
var response = context.Response;
////Èç¹ûÊÇjsµÄajaxÇëÇ󣬻¹¿ÉÒÔÉèÖÿçÓòµÄipµØÖ·Óë²ÎÊý
//context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//ºǫ́¿çÓòÇëÇó£¬Í¨³£ÉèÖÃΪÅäÖÃÎļþ
//context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//ºǫ́¿çÓò²ÎÊýÉèÖã¬Í¨³£ÉèÖÃΪÅäÖÃÎļþ
//context.Response.AppendHeader("Access-Control-Allow-Method", "post");//ºǫ́¿çÓòÇëÇóÉèÖã¬Í¨³£ÉèÖÃΪÅäÖÃÎļþ
context.Response.ContentType = "text/plain;charset=UTF-8";//¸æË߿ͻ§¶Ë·µ»ØµÄContentTypeÀàÐÍΪ´¿Îı¾¸ñʽ£¬±àÂëΪUTF-8
context.Response.AddHeader("Content-type", "text/plain");//Ìí¼ÓÏìӦͷÐÅÏ¢
context.Response.ContentEncoding = Encoding.UTF8;
string returnObj = null;//¶¨Òå·µ»Ø¿Í»§¶ËµÄÐÅÏ¢
if (request.HttpMethod == "POST" && request.InputStream != null)
{
//´¦Àí¿Í»§¶Ë·¢Ë͵ÄÇëÇó²¢·µ»Ø´¦ÀíÐÅÏ¢
returnObj = HandleRequest(request, response);
}
else
{
returnObj = $"²»ÊÇpostÇëÇó»òÕß´«¹ýÀ´µÄÊý¾ÝΪ¿Õ";
}
var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//ÉèÖÿͻ§¶Ë·µ»ØÐÅÏ¢µÄ±àÂë
try
{
using (var stream = response.OutputStream)
{
//°Ñ´¦ÀíÐÅÏ¢·µ»Øµ½¿Í»§¶Ë
stream.Write(returnByteArr, 0, returnByteArr.Length);
}
}
catch (Exception ex)
{
Debug.LogError($"ÍøÂç±ÄÁË£º{ex.ToString()}");
}
Debug.Log($"ÇëÇó´¦ÀíÍê³É£º{guid},ʱ¼ä£º{DateTime.Now.ToString()}\r\n");
}
private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
{
string data = null;
try
{
var byteList = new List<byte>();
var byteArr = new byte[2048];
int readLen = 0;
int len = 0;
//½ÓÊÕ¿Í»§¶Ë´«¹ýÀ´µÄÊý¾Ý²¢×ª³É×Ö·û´®ÀàÐÍ
do
{
readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);
len += readLen;
byteList.AddRange(byteArr);
} while (readLen != 0);
data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);
//»ñÈ¡µÃµ½Êý¾Ýdata¿ÉÒÔ½øÐÐÆäËû²Ù×÷
}
catch (Exception ex)
{
response.StatusDescription = "404";
response.StatusCode = 404;
Debug.LogError($"ÔÚ½ÓÊÕÊý¾Ýʱ·¢Éú´íÎó:{ex.ToString()}");
return $"ÔÚ½ÓÊÕÊý¾Ýʱ·¢Éú´íÎó:{ex.ToString()}";//°Ñ·þÎñ¶Ë´íÎóÐÅÏ¢Ö±½Ó·µ»Ø¿ÉÄܻᵼÖÂÐÅÏ¢²»°²È«£¬´Ë´¦½ö¹©²Î¿¼
}
response.StatusDescription = "200";//»ñÈ¡»òÉèÖ÷µ»Ø¸ø¿Í»§¶ËµÄ HTTP ״̬´úÂëµÄÎı¾ËµÃ÷¡£
response.StatusCode = 200;// »ñÈ¡»òÉèÖ÷µ»Ø¸ø¿Í»§¶ËµÄ HTTP ״̬´úÂë¡£
Debug.Log($"½ÓÊÕÊý¾ÝÍê³É:{data.Trim()},ʱ¼ä£º{DateTime.Now.ToString()}");
return $"½ÓÊÕÊý¾ÝÍê³É";
}
#endregion
/// <summary>
/// Ìí¼ÓÊý×ÖÈËÏûÏ¢´¦Àí·½·¨
/// </summary>
/// <param name="handlerFun">json£¬ÏûÏ¢Ò»¶¨°üº¬ÒÔÏÂ×ֶΣºint eventid£¨²Ù×÷id£©,string commond Ö¸Áî </param>
public void SetHandler_szr(Action<JObject> handlerFun)
{
handleFun_szr = handlerFun;
}
/// <summary>
/// Ìí¼Ó»úÆ÷ÈËÏûÏ¢´¦Àí·½·¨
/// </summary>
/// <param name="handlerFun">json£¬ÏûÏ¢Ò»¶¨°üº¬ÒÔÏÂ×ֶΣºint eventid£¨²Ù×÷id£©,string commond Ö¸Áî </param>
public void SetHandler_jqr(Action<JObject> handlerFun)
{
handleFun_jqr = handlerFun;
}
/// <summary>
/// Ìí¼ÓÎÞÈË»úÏûÏ¢´¦Àí·½·¨
/// </summary>
/// <param name="handlerFun">json£¬ÏûÏ¢Ò»¶¨°üº¬ÒÔÏÂ×ֶΣºint eventid£¨²Ù×÷id£©,string commond Ö¸Áî </param>
public void SetHandler_wrj(Action<JObject> handlerFun)
{
handleFun_wrj = handlerFun;
}
/// <summary>
/// Ìí¼ÓÆäËüÀàÐÍÏûÏ¢´¦Àí·½·¨
/// </summary>
/// <param name="handlerFun">json£¬ÏûÏ¢Ò»¶¨°üº¬ÒÔÏÂ×ֶΣºint eventid£¨²Ù×÷id£©,string commond Ö¸Áî </param>
public void SetHandler_other(Action<JObject> handlerFun)
{
handleFun_other = handlerFun;
}
/// <summary>
/// ·¢ËÍÏûÏ¢£¬ (ÍêÈ«°æ£¬¿ÉÌí¼Ó×Ô¶¨Òå×Ö¶Î)
/// </summary>
/// <param name="msg">json¸ñʽ£¬µ±»Ø¸´ÏûϢʱ±ØÐë°üº¬ÒÔϼ¸¸ö×ֶΣºint eventid(»Ø¸´id),ResultState result£¨½á¹û£©,string msg£¨Ê§°Ü×ֶΣ©</param>
public void SendMsgToSDK(string msg)
{
if (handler != null)
{
handler.SendMsg(msg);
}
}
/// <summary>
/// ·¢ËÍÏûÏ¢£¬(¼òÒװ棬ֻ°üº¬»ù´¡×Ö¶Î)
/// </summary>
/// <param name="eventid"></param>
/// <param name="result"></param>
/// <param name="msg"></param>
public void SendMsgToSDK(int eventid, ResultState result, string msg = null)
{
if (result != ResultState.SUCCESS && msg == null)
{
Debug.LogError("ʧ°Ü±ØÐë´«Ô­Òò");
}
else
{
if (handler != null)
{
handler.SendMsg(JsonConvert.SerializeObject(new { eventid = eventid, result = result, msg = msg == null ? "" : msg }));
}
}
}
}
/// <summary>
/// »Ø¸´µÄ¼¶±ð
/// </summary>
public enum ResultState
{
SUCCESS = 1,
/// <summary>
/// ´Ë²Ù×÷ʧ°Ü£¬±¾´Î·ÂÕæ²âÊÔ¼ÌÐø½øÐÐ
/// </summary>
FAILED_WARNNING = 2,
/// <summary>
/// ´Ë²Ù×÷ʧ°Ü£¬±¾´Î·ÂÕæ²âÊÔÖжÏ
/// </summary>
FAILED_ERROR = 3
}