二、PC集成unity(2)Socket通信
unity 端代码using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Net.Sockets;using System.Text;using UnityEngine;public class U2F_Connection : MonoBehaviour{ TcpClient client; int PortNo = 2023; byte[] RecBuffer; string ErrorInfo; public static U2F_Connection Instance = null; public string _ReceivedMsg; public Texture2D TestTex; public bool IsConnected = false; public float frameCount = 0; void Awake() { Instance = this; //Init(); } public void Init() { try { //获取Winform传过来的端口号 //string[] Args = Environment.GetCommandLineArgs(); //if (Args.Length > 3) // PortNo = int.Parse(Args); //连接到服务器 client = new TcpClient(); //client.Connect("127.0.0.1", PortNo); client.Connect("172.21.41.99", PortNo); RecBuffer = new byte; //数据发送 //SendWinMsg("Unity is ready ..."); //string dataStr = Texture2DToBase64ByPng(); //SendWinMsg(dataStr);发送数据给Winform client.GetStream().BeginRead(RecBuffer, 0, client.ReceiveBufferSize, ReceiveWinMsg, null); IsConnected = true; } catch (Exception) { } } /// <summary> /// 发送消息给WPF /// </summary> /// <param name="msg"></param> public void SendWinMsg(string msg) { try { NetworkStream ns = client.GetStream(); byte[] data = Encoding.UTF8.GetBytes(msg); ns.Write(data, 0, data.Length); ns.Flush(); } catch (Exception ex) { ErrorInfo = ex.Message; } } /// <summary> /// 接收WPF的消息 /// </summary> /// <param name="ar"></param> public void ReceiveWinMsg(IAsyncResult ar) { try { //清空ErrorInfo ErrorInfo = ""; int bytesRead = client.GetStream().EndRead(ar); if (bytesRead < 1) return; else { _ReceivedMsg = Encoding.UTF8.GetString(RecBuffer, 0, bytesRead); } client.GetStream().BeginRead(RecBuffer, 0, client.ReceiveBufferSize, ReceiveWinMsg, null); } catch (Exception ex) { ErrorInfo = ex.Message; } } private void OnDestroy() { if (client != null) { client.Close(); } } public string TextureToBase64() { Texture2D texture2D = TestTex; //byte[] imageData = texture2D.EncodeToPNG(); byte[] imageData = new byte; Color c; for (int i = 0; i < texture2D.height; i++) { for (int j = 0; j < texture2D.width; j++) { c = texture2D.GetPixel(j, i); imageData = (byte)(c.r * 255.0f + 0.5f); imageData = (byte)(c.g * 255.0f + 0.5f); imageData = (byte)(c.b * 255.0f + 0.5f); imageData = (byte)(c.a * 255.0f + 0.5f); ; } } string baser64 = Convert.ToBase64String(imageData); Debug.Log(baser64); //WriteFile(baser64, Application.persistentDataPath + "TexData01.txt"); return baser64; } public String Texture2DToBase64ByPng() { Texture2D texture2D = TestTex; byte[] bytesArr = texture2D.EncodeToPNG(); string strbaser64 = Convert.ToBase64String(bytesArr); //WriteFile(strbaser64, Application.persistentDataPath + "Texture2DToBase64ByPng.txt"); return strbaser64; }}PC 端代码或另一端unity
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Windows.Forms;namespace Container{ public class F2U_Connection { public delegate void msgDelegate(string msg); private static F2U_Connection _instance; private Socket serverSocket; private Socket clientSocket; public static int conPort; private Thread listenThread; private Thread receiveThread; private bool isListening = false; private bool isReceiving = false; private static byte[] result; public msgDelegate StatusCallBack; public msgDelegate msgCallBack; private string _stateInfo; private string _receiveMsg; /// <summary> /// 单例 /// </summary> public static F2U_Connection Instance { get { if (F2U_Connection._instance == null) { F2U_Connection._instance = new F2U_Connection(); } return F2U_Connection._instance; } } public string receiveMsg { get { return this._receiveMsg; } set { this._receiveMsg = value; msgDelegate _msgDelegate = this.msgCallBack; if (_msgDelegate != null) { _msgDelegate(this._receiveMsg); } else { } } } public string statusInfo { get { return this._stateInfo; } set { this._stateInfo = value; msgDelegate statusCallBack = this.StatusCallBack; if (statusCallBack != null) { statusCallBack(this._stateInfo); } else { } } } static F2U_Connection() { F2U_Connection._instance = null; F2U_Connection.conPort = 2023; //F2U_Connection.result = new byte; F2U_Connection.result = new byte; } /// <summary> /// 等待客户端的连接 并且创建与之通信的Socket /// </summary> private void listenClientConnect() { while (this.isListening) { try { this.clientSocket = this.serverSocket.Accept(); this.receiveThread = new Thread(new ParameterizedThreadStart(this.ReceiveU3DMsg)); this.isReceiving = true; this.receiveThread.Start(this.clientSocket); //MessageBox.Show("unity connnected winform."); //Program.AppForm.CallInvokeUIUpdate("codeUpdateLaeleText"); //连接成功处理 } catch (Exception exception) { this.statusInfo = string.Concat("监听线程错误:", exception.Message); } } } public void QuitServer() { try { if (this.serverSocket != null) { this.serverSocket.Close(); } if (this.clientSocket != null) { this.clientSocket.Close(); } this.isListening = false; this.listenThread.Join(); this.isReceiving = false; this.receiveThread.Join(); } catch (Exception exception) { MessageBox.Show(exception.Message + ".\nQuitServer."); } } private void ReceiveU3DMsg(object cliSocket) { Socket socket = (Socket)cliSocket; while (this.isReceiving) { try { //实际接收到的有效字符 int num = socket.Receive(F2U_Connection.result); if (num > 1) { this.receiveMsg = Encoding.UTF8.GetString(F2U_Connection.result, 0, num); //Program.AppForm.CallInvokeUIUpdate("updateFrameRate", this.receiveMsg); //接受消息处理 } } catch (Exception exception2) { Exception exception = exception2; try { this.statusInfo = string.Concat("接收消息错误:", exception.Message); this.clientSocket.Shutdown(SocketShutdown.Both); this.clientSocket.Close(); } catch (Exception exception1) { if (this.isReceiving == false) { return; } MessageBox.Show(exception1.Message + ".\n接收消息错误2."); } } } } public void SendU3DMsg(string msg) { if ((this.clientSocket == null ? true : !this.clientSocket.Connected)) { this.statusInfo = "Unity端离线。"; } else { this.clientSocket.Send(Encoding.UTF8.GetBytes(msg)); } } public void StartServer() { //在服务端创建一个负责监听IP和端口号的Socket //IPAddress pAddress = IPAddress.Parse("127.0.0.1"); IPAddress pAddress = IPAddress.Parse("172.21.41.99"); this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定端口号 this.serverSocket.Bind(new IPEndPoint(pAddress, F2U_Connection.conPort)); //设置监听 this.serverSocket.Listen(10); this.statusInfo = string.Concat("启动监听:", this.serverSocket.LocalEndPoint.ToString(), "成功"); //创建监听线程 this.listenThread = new Thread(new ThreadStart(this.listenClientConnect)); this.isListening = true; this.listenThread.Start(); } public string GetConnectState() { return this.statusInfo; } }}
注意:支持Unity和Unity互通,也支持Unity和PC程序互通
页:
[1]