123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets; //调用socket
- using System.Text;
- using System.Threading; //调用线程
- using UnityEngine;
- using System.IO;
- using System.Net.NetworkInformation;
- using LitJson;
- //
- public class server : MonoBehaviour
- {
- //定义变量(与GUI一致)
- private string info = "NULL"; //状态信息
- private string recMes = "NULL"; //接收到的信息
- private int recTimes = 0; //接收到的信息次数
- private string inputIp = "192.168.50.17"; //ip地址(本地)
- private string inputPort = "8089"; //端口值
- private string Message = "NULL"; //用以发送的信息
- private Socket socketWatch;
- private static Socket socketWatchudp; //用以监听的套接字
- public static Socket socketSend; //用以和客户端通信的套接字
- private bool isSendData = false; //是否点击发送数据按钮
- private bool clickConnectBtn = false; //是否点击监听按钮
- public Queue<String> queueRecMsg;
- // Start is called before the first frame update
- void Start()
- {
- inputIp = GetIP();
- ClickConnect();
- // TimerMgr.Instance.CreateTimer(() => { SendData(); }, 0.1f, -1);
- queueRecMsg = new Queue<string>();
- // Debug.Log(GetIP());
- }
- // Update is called once per frame
- void Update()
- {
- }
- /// <summary>
- /// 获取本机IP
- /// </summary>
- /// <param name="Addfam">要获取的IP类型</param>
- /// <returns></returns>
- public string GetIP()
- {
- return GetLocalIPAddress();
- }
- //建立tcp通信链接
- private void ClickConnect()
- {
- int _port = Convert.ToInt32(inputPort); //获取端口号(32位,4个字节)
- string _ip = GetLocalIPAddress(); //获取ip地址
- Debug.Log(" ip 地址是 :" + _ip);
- Debug.Log(" 端口号是 :" + _port);
- clickConnectBtn = true; //点击了监听按钮,更改状态
- info = "ip地址是 : " + _ip + "端口号是 : " + _port;
- //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
- socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPAddress ip = IPAddress.Parse(inputIp);
- IPEndPoint point = new IPEndPoint(ip, _port); //创建对象端口
- socketWatch.Bind(point); //绑定端口号
- Debug.Log("TCP监听成功!");
- info = "监听成功";
- socketWatch.Listen(10); //设置监听,最大同时连接10台
- //创建监听线程
- Thread thread = new Thread(Listen);
- thread.IsBackground = true;
- thread.Start(socketWatch);
- }
- static IPEndPoint broadcastEndPoint;
- void ReceiveMsg()
- {
- byte[] data = new byte[1024];
- EndPoint point = new IPEndPoint(IPAddress.Any, 0);
- while (true)
- {
- int length = socketWatchudp.ReceiveFrom(data, ref point);
- string mes = Encoding.UTF8.GetString(data, 0, length);
- Debug.Log("服务器从" + ((IPEndPoint)point).Address + "端口:" + ((IPEndPoint)point).Port + "收到了消息:" + mes);
- }
- }
- string GetLocalIPAddress()
- {
- var host = Dns.GetHostEntry(Dns.GetHostName());
- foreach (var ip in host.AddressList)
- {
- if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
- {
- return ip.ToString();
- }
- }
- throw new System.Exception("No network adapters with an IPv4 address in the system!");
- }
- static List<Socket> sockets = new List<Socket>();
- /// <summary>
- /// 等待客户端的连接 并且创建与之通信的Socket
- /// </summary>
- void Listen(object o)
- {
- try
- {
- Socket socketWatch = o as Socket;
- while (true)
- {
- socketSend = socketWatch.Accept(); //等待接收客户端连接
- sockets.Add(socketSend);
- Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
- info = socketSend.RemoteEndPoint.ToString() + " 连接成功!";
- Thread r_thread = new Thread(Received); //开启一个新线程,执行接收消息方法
- r_thread.IsBackground = true;
- r_thread.Start(socketSend);
- // Thread s_thread = new Thread(SendMessage); //开启一个新线程,执行发送消息方法
- // s_thread.IsBackground = true;
- // s_thread.Start(socketSend);
- }
- }
- catch { }
- }
- // 服务器端不停的接收客户端发来的消息
- void Received(object o)
- {
- try
- {
- Socket socketSend = o as Socket;
- while (true)
- {
- byte[] buffer = new byte[1024 * 6]; //客户端连接服务器成功后,服务器接收客户端发送的消息
- int len = socketSend.Receive(buffer); //实际接收到的有效字节数
- if (len == 0)
- {
- Debug.Log("断开 " );
- break;
- }
- string recvStr = Encoding.UTF8.GetString(buffer, 0, len);
- Debug.Log("收到信息 " + recvStr);
- try
- {
- string[] q1 = recvStr.Split(new char[2] { 'R', 'T' });
- double q = double.Parse(q1[1]);
- string[] xRo = recvStr.Split(new char[2] { 'X', 'R' });
- string[] yRo = recvStr.Split(new char[2] { 'Y', 'X' });
- string[] zRo = recvStr.Split(new char[2] { 'Z', 'Y' });
- Debug.Log("收到x " + xRo[0]);
- #region 角度
- //float xro = -float.Parse(yRo[1]);
- //float yro = 180 - float.Parse(zRo[1]);
- //float zro = float.Parse(xRo[1]);
- float xro = -float.Parse(zRo[1]);
- float zro = -(180 - float.Parse(yRo[1]));
- float yro = float.Parse(xRo[1]);
- Vector3 jd = new Vector3(xro, 1.352f, zro);
- Quaternion q2 = Quaternion.Euler(jd);
- Debug.Log("角度为" + jd);
- #endregion
- #region 加速度
- //string[] xA = recvStr.Split(new char[2] { 'D', 'E' });
- //string[] yA = recvStr.Split(new char[2] { 'E', 'F' });
- //string[] zA = recvStr.Split(new char[2] { 'F', 'G' });
- //xa = float.Parse(xA[1]);
- //ya = float.Parse(yA[1]);
- //za = float.Parse(zA[1]);
- ////Debug.Log("加速度为" + xa+' '+ya+' '+za);
- //#endregion
- //#region 弯度
- //string[] wD= recvStr.Split(new char[2] { 'G', 'H' });
- //wd= int.Parse(wD[1]);
- #endregion
- //msgQueue.Enqueue(recvStr);
- //SZ90Y90X90R20T
- }
- catch
- {
- }
- }
- // Debug.Log("接收到的消息:" + socketSend.RemoteEndPoint + ":" + recvStr);
- // recMes = str;
- recTimes++;
- info = "接收到一次数据,接收次数为:" + recTimes;
- // Debug.Log("接收数据次数:" + recTimes);
- // queueRecMsg.Enqueue(recMes);
-
- // }
- }
- catch { }
- }
- public void SendData()
- {
- if (socketSend != null)
- Debug.Log("sendData " + SocketExtensions.IsConnected(socketSend));
- if (socketSend!=null&& SocketExtensions.IsConnected(socketSend))
- {
- if(NetWorkLANManager.Instance.createDesMsg.Count>0)
- {
- Message = NetWorkLANManager.Instance.createDesMsg.Dequeue();
- isSendData = true;
- return;
- }
- else if (NetWorkLANManager.Instance.queueMsg.Count > 0)
- {
- Message = NetWorkLANManager.Instance.queueMsg.Dequeue();
- isSendData = true;
- }
-
- }
- }
- // 服务器端不停的向客户端发送消息
- public static void SendMessage(JsonData data)
- {
- return;
- if (socketSend == null)
- {
- return;
- }
- for (int i = 0; i < sockets.Count; i++)
- {
- try
- {
- byte[] sendByte = Encoding.UTF8.GetBytes(data.ToJson());
- Debug.Log("发送的数据为 :" + data.ToJson());
- Debug.Log("发送的数据字节长度 :" + sendByte.Length);
- sockets[i].Send(sendByte);
- }
- catch { }
- }
- }
- // 关闭连接,释放资源
- private void OnDisable()
- {
- Debug.Log("begin OnDisable()");
- if (clickConnectBtn)
- {
- }
- Debug.Log("end OnDisable()");
- }
- private void OnDestroy()
- {
- socketWatch.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
- socketWatch.Close();
- socketWatch.Dispose(); //关闭Socket连接并释放所有相关资源
- socketWatchudp.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
- socketWatchudp.Close();
- socketWatchudp.Dispose();
- for (int i = 0; i < sockets.Count; i++)
- {
- sockets[i].Dispose();
- }
- }
- //交互界面(代码创建)
- void OnGUI()
- {
- /*
- GUI.color = Color.black; //字体颜色
- GUI.Label(new Rect(65, 10, 80, 20), "状态信息");
- GUI.Label(new Rect(155, 10, 80, 70), info);
- GUI.Label(new Rect(65, 80, 80, 20), "接收到消息:");
- GUI.Label(new Rect(155, 80, 80, 20), recMes);
- GUI.Label(new Rect(65, 120, 80, 20), "发送的消息:");
- Message = GUI.TextField(new Rect(155, 120, 100, 20), Message, 20);
- GUI.Label(new Rect(65, 160, 80, 20), "本机ip地址:");
- inputIp = GUI.TextField(new Rect(155, 160, 100, 20), inputIp, 20);
- GUI.Label(new Rect(65, 200, 80, 20), "本机端口号:");
- inputPort = GUI.TextField(new Rect(155, 200, 100, 20), inputPort, 20);
- if (GUI.Button(new Rect(65, 240, 60, 20), "开始监听"))
- {
- ClickConnect(); //点击开始
- }
- if (GUI.Button(new Rect(65, 280, 60, 20), "发送数据"))
- {
- isSendData = true; //发送数据
- }*/
- }
- }
|