发送的电脑
using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; using System.IO; using System; public class SendPhoto:MonoBehaviour { private Socket socket = null; private IPEndPoint endPoint = null; void Start() { InitSocketEnv(); } //绑定在发送按钮上 public void SendMegEvent() { SendPhotoMessage("123.jpg"); } void SendPhotoMessage(string fileName) { string path = @"D:\test\"; print(path + fileName); FileStream fs = new FileStream(path + fileName,FileMode.OpenOrCreate,FileAccess.Read); BinaryReader strread = new BinaryReader(fs); byte[] byt = new byte[fs.Length]; strread.Read(byt,0,byt.Length - 1); socket.Send(byt); fs.Close(); socket.Close(); } void InitSocketEnv() { socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //接收电脑的IP endPoint = new IPEndPoint(IPAddress.Parse("192.168.0.76"),9001); socket.Connect(endPoint); } void OnDestory() { socket.Close(); } }
//发送的电脑
using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; using System.Collections.Generic; using System; public class RecivePhoto:MonoBehaviour { private Socket m_socket = null; private IPEndPoint m_ipEp = null; private Thread m_thread = null; private bool isRunningThread = false; private Queue<byte[]> m_queue; void Start() { m_queue = new Queue<byte[]>(); InitSocketEnv(); } // Update is called once per frame void Update() { if(m_queue.Count > 0) { Debug.Log(m_queue.Count); byte[] temp = m_queue.Dequeue(); FileStream fs = File.Create("D:/test/123.png"); fs.Write(temp,0,temp.Length); fs.Close(); } } void ReciveMeg() { while(isRunningThread) { Socket socket = m_socket.Accept(); //1M的大小 byte[] buffer = new byte[1024*1024]; socket.Receive(buffer,buffer.Length,SocketFlags.None); m_queue.Enqueue(buffer); socket.Close(); } Debug.Log("stop"); } void InitSocketEnv() { m_socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); //接收电脑的IP m_ipEp = new IPEndPoint(IPAddress.Parse("192.168.0.166"),9001); m_socket.Bind(m_ipEp); m_socket.Listen(5); isRunningThread = true; m_thread = new Thread(ReciveMeg); m_thread.Start(); } void OnDistory() { isRunningThread = false; m_socket.Close(); } }
标签:传送,socket,void,System,private,局域网,unity,new,using From: https://www.cnblogs.com/zqiang0803/p/16982724.html