| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.Text;
- using System;
- using System.Net;
- using System.IO;
- public class SocketManager : MonoBehaviour
- {
- // Use this for initialization
- public SocketClient serverConnerction;
- int number = 0;
- string date = "{\"type\":" + 0 + "}";
- void Start()
- {
- //启动连接
- StartServerConnerction();
- }
- // Update is called once per frame
- void Update()
- {
- HandleTasks(serverConnerction.receiveQueue);
- }
- /// <summary>
- /// 程序关闭前,关闭Socket连接
- /// </summary>
- private void OnDisable()
- {
- ClosedServerConnerction();
- }
- #region Socket双向数据
- /// <summary>
- /// 开启双向接收数据连接
- /// </summary>
- public void StartServerConnerction()
- {
- serverConnerction = new SocketClient("192.168.0.120", "8000");
- serverConnerction.OnConnectAsync();
- }
- public void SendData()
- {
- //serverConnerction.Send(date);
- }
- /// <summary>
- /// 关闭双向接收数据连接
- /// </summary>
- public void ClosedServerConnerction()
- {
- if (serverConnerction != null)
- {
- serverConnerction.Closed();
- }
- }
- #endregion
- /// <summary>
- /// 任务分发
- /// </summary>
- /// <param name="data_Queue"></param>
- void HandleTasks(Queue<byte[]> data_Queue)
- {
- if (data_Queue.Count > 0)
- {
- byte[] data = data_Queue.Dequeue();
- //标志位
- byte[] bufferTag = new byte[4];
- int idx = 20;
- Array.Copy(data, idx, bufferTag, 0, bufferTag.Length);
- //长度
- byte[] newLen = new byte[4];
- int idx_1 = 10;
- Array.Copy(data, idx_1, newLen, 0, newLen.Length);
- //包体
- byte[] bufferBody = new byte[int.Parse(GetString(newLen))];
- int idx_2 = 32;
- Array.Copy(data, idx_2, bufferBody, 0, bufferBody.Length);
- string json = GetString(bufferBody);//减去包头的最终json数据
- //string bodyJson = HttpUtility.UrlDecode(json, Encoding.UTF8);
- //print(bodyJson);
- if (GetString(bufferTag).Contains("LOGI"))//登录操作
- {
-
- }
- }
- }
- string GetString(byte[] buffer)
- {
- return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
- }
- /// <summary>
- /// 登录格式
- /// </summary>
- /// <param name="user"></param>
- /// <param name="password"></param>
- /// <returns></returns>
- public string LoginString(string user, string password)
- {
- string result = null; ;
- string json = "{\"account\":\"" + user + "\",\"password\":\"" + password + "\"}";
- string len = "";
- if (json.Length.ToString().Length < 4)
- {
- for (int i = 0; i < 4 - json.Length.ToString().Length; i++)
- {
- len += "0";
- }
- len += json.Length.ToString();
- }
- result = "aa00838961" + len + "00 CLTLOGI0000avcd" + json + "ff";
- print("发送给服务器的帐号密码:"+result);
- return result;
- }
- }
|