UnityTCP发送接收图片

发送端代码:

using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System;

public class TCPClient : MonoBehaviour
{
    private Socket socket = null;
    private IPEndPoint endPoint = null;

    public string ip;
    public int port;
    string imagename = "1.jpg";
    // Use this for initialization
    void Start()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
        socket.Connect(endPoint);
    }
    public void SendMegEvent()
    {
        SendImage(imagename);
    }

    void SendImage(string fileName)
    {
        FileStream fs = new FileStream(Application.streamingAssetsPath + "/" + fileName, FileMode.OpenOrCreate, FileAccess.Read);
        BinaryReader strread = new BinaryReader(fs);
        byte[] bt = new byte[fs.Length];
        strread.Read(bt, 0, bt.Length - 1);
        socket.Send(bt);
        fs.Close();
        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 TCPServer : 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;

    public string ip;
    public int port;

    // Use this for initialization
    void Start()
    {
        m_queue = new Queue<byte[]>();
        m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        m_ipEp = new IPEndPoint(IPAddress.Parse(ip), port);
        m_socket.Bind(m_ipEp);
        m_socket.Listen(5);
        isRunningThread = true;
        m_thread = new Thread(ReciveMeg);
        m_thread.Start();
    }

    void Update()
    {
        if (m_queue.Count > 0)
        {
            byte[] temp = m_queue.Dequeue();
            FileStream fs = File.Create(Application.streamingAssetsPath + "/" + "1.jpg");
            fs.Write(temp, 0, temp.Length);
            fs.Close();
        }
    }

    void ReciveMeg()
    {
        while (isRunningThread)
        {
            Socket socket = m_socket.Accept();
            byte[] buffer = new byte[2000000];
            socket.Receive(buffer, buffer.Length, SocketFlags.None);
            m_queue.Enqueue(buffer);
            socket.Close();
        }
    }
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值