Unity3D读取Socket的二进制图片

服务端:C#的Winfrom开发服务器,数据库是Access

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.NET;
using System.Net.Sockets;
using System.Threading;


namespace WindowsForms_Server
{
    public partial class Form1 : Form
    {
        OleDbConnection conn; //Jet OLEDB:Database Password=
        OleDbCommand cmd;
        OleDbDataReader dr;
        DataTable dt;
        string str = null;
        public Form1()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false; 
            //数据库的地址
            conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\DataSQL\\DB.mdb"); //Jet OLEDB:Database Password=
            //conn.Open();
            //SaveImage("C:\\Users\\123\\Desktop\\timg.jpg",conn);  //  两个 \\ 代表一个 / 字符串 (以下两种也都可以用)
            //SaveImage(@"C:\Users\123\Desktop\timg.jpg", conn);
            //SaveImage("C:/Users/123/Desktop/timg.jpg", conn);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            conn.Open();
            cmd = conn.CreateCommand();
            cmd.CommandText = "select * from user_DB";  //表名
            dr = cmd.ExecuteReader();
            dt = new DataTable();
            //文件名
            if (dr.HasRows)
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    dt.Columns.Add(dr.GetName(i));
                }
                dt.Rows.Clear();
            }
            while (dr.Read())
            {
                DataRow row = dt.NewRow();
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    row[i] = dr[i];
                }
                dt.Rows.Add(row);
            }


            cmd.Dispose();
            conn.Close();
            dataGridView1.DataSource = dt;
        }


        private void button2_Click(object sender, EventArgs e)
        {
            conn.Open();
            cmd = conn.CreateCommand();
            cmd.CommandText = "select * from user_DB where ID=2";
            dr = cmd.ExecuteReader();
            dt = new DataTable();
            if (dr.HasRows)
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    dt.Columns.Add(dr.GetName(i));
                }
                dt.Rows.Clear();
            }
            while (dr.Read())
            {
                DataRow row = dt.NewRow();
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    row[i] = dr[i];
                }
                dt.Rows.Add(row);
            }
            cmd.Dispose();
            conn.Close();
            dataGridView1.DataSource = dt;
        }


        private void button3_Click(object sender, EventArgs e)  //读取图片
        {
            byte[] buff = null;
            Image image = null;
            conn.Open();
            cmd = conn.CreateCommand();
            cmd.CommandText = "select img from user_DB where ID=5";
            OleDbParameter p = new OleDbParameter();
            p.Value = buff;
            cmd.Parameters.Add(p);
            cmd.ExecuteNonQuery();
            dr = cmd.ExecuteReader();
            dr.Read();
            buff = (byte[])dr[0];
            //while (dr.Read())
            //{
            //    buff = (byte[])dr.GetValue(0);


            //}
            dr.Close();
            cmd.Dispose();
            conn.Close();


            MemoryStream ms = new MemoryStream(buff);
            //ms.Position = 0;
            image = System.Drawing.Image.FromStream(ms);


            //Image image = Image.FromStream(ms);
            Bitmap bmpt = new Bitmap(image);
            pictureBox1.Image = bmpt;


        }
        private void SaveImage(string filepath, OleDbConnection con) //将图片以长二进制的形式存入数据库(只有如此才能读取图片
        {
            con.Open();
            FileStream fs = new FileStream(filepath, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            byte[] buff = br.ReadBytes((int)fs.Length);
            OleDbCommand com = new OleDbCommand("update user_DB set img=@pic where ID=5", con);
            com.Parameters.AddWithValue("@pic", buff);
            com.ExecuteNonQuery();


            con.Close();
            com.Dispose();


            br.Close();
            fs.Close();


        }


        private void button4_Click(object sender, EventArgs e)  //浏览文件
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = "D:\\";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtSelectFile.Text = ofd.FileName;  //这里显示的文件路径会自动转义成 \\双斜杠
            }
            if (txtSelectFile.Text == "" || txtSelectFile.Text == null)
            {
                str = null;
            }
            else
            {
                str = txtSelectFile.Text;
            }
            ofd.FileName = null;    // 置空,不然点击此处时不选定,取消的话会报错
            ofd = null;         // 置空,不然点击此处时不选定,取消的话会报错
        }


        private void button5_Click(object sender, EventArgs e)  //上传保存文件
        {
            if (str != null)
            {
                SaveImage(str, conn);
                txtSelectFile.Text = null;
                str = null;
            }
        }


        Thread threadWatch = null; // 负责监听客户端连接请求的 线程; 
        Socket socketWatch = null;
        Dictionary<string, Socket> dict = new Dictionary<string, Socket>();  //存储客户端对象池
        Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>(); 
        private void button6_Click(object sender, EventArgs e)
        {
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            IPAddress ad = IPAddress.Parse("127.0.0.1");
            IPEndPoint end = new IPEndPoint(ad, 8080);


            try
            {
                socketWatch.Bind(end);
            }
            catch (SocketException se)
            {
                MessageBox.Show("异常:" + se.Message);
                return; 
            }
            socketWatch.Listen(10);
            //创建负责监听的线程; 
            threadWatch = new Thread(WatchConnecting);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            textBox1.Text = "服务器启动成功!" + "\r\n";
        }
        void WatchConnecting()
        {
            while (true)  // 持续不断的监听客户端的连接请求; 
            {
                // 开始监听客户端连接请求,Accept方法会阻断当前的线程; 
                Socket sokConnection = socketWatch.Accept(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字; 
                lbOnline.Items.Add(sokConnection.RemoteEndPoint.ToString());
                // 将与客户端连接的 套接字 对象添加到集合中; 
                dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection); 
                Thread thr = new Thread(RecMsg);
                thr.IsBackground = true;
                thr.Start(sokConnection);
                textBox1.Text = "客户端连接成功!" + "\r\n";
                dictThread.Add(sokConnection.RemoteEndPoint.ToString(), thr);  //  将新建的线程 添加 到线程的集合中去。 
            }
        }
        void RecMsg(object sokConnectionparn)
        {
            Socket sokClient = sokConnectionparn as Socket;
            while (true)
            {
                // 定义一个2M的缓存区; 
                byte[] arrMsgRec = new byte[1024 * 1024 * 2];
                // 将接受到的数据存入到输入  arrMsgRec中; 
                int length = -1;
                try
                {
                    length = sokClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度; 
                }
                catch (SocketException se)
                {
                    textBox1.Text = "异常:" + se.Message;
                    // 从 通信套接字 集合中删除被中断连接的通信套接字; 
                    dict.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象; 
                    dictThread.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从列表中移除被中断的连接IP 
                    lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString()); 
                    break;
                }
                catch (Exception e)
                {
                    textBox1.Text = "异常:" + e.Message;
                    // 从 通信套接字 集合中删除被中断连接的通信套接字; 
                    dict.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从通信线程集合中删除被中断连接的通信线程对象; 
                    dictThread.Remove(sokClient.RemoteEndPoint.ToString());
                    // 从列表中移除被中断的连接IP 
                    lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString()); 
                    break;
                }
                if (arrMsgRec[0] == 0)  // 表示接收到的是数据; 
                {
                    string strMsg = System.Text.Encoding.Default.GetString(arrMsgRec, 1, length - 1);// 将接受到的字节数据转化成字符串; 
                    
                }
                if (arrMsgRec[0] == 1) // 表示接收到的是文件; 
                {
                    SaveFileDialog sfd = new SaveFileDialog();


                    if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {// 在上边的 sfd.ShowDialog() 的括号里边一定要加上 this 否则就不会弹出 另存为 的对话框,而弹出的是本类的其他窗口,,这个一定要注意!!!【解释:加了this的sfd.ShowDialog(this),“另存为”窗口的指针才能被SaveFileDialog的对象调用,若不加thisSaveFileDialog 的对象调用的是本类的其他窗口了,当然不弹出“另存为”窗口。】 


                        string fileSavePath = sfd.FileName;// 获得文件保存的路径; 
                        // 创建文件流,然后根据路径创建文件; 
                        using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
                        {
                            fs.Write(arrMsgRec, 1, length - 1);
                            //ShowMsg("文件保存成功:" + fileSavePath);
                        }
                    }
                }
            }
        }
        private void button7_Click(object sender, EventArgs e)
        {
            byte[] buff = new byte[1024 * 1024 * 2];
            conn.Open();
            cmd = conn.CreateCommand();
            cmd.CommandText = "select img from user_DB where ID=5";
            OleDbParameter p = new OleDbParameter();
            p.Value = buff;
            cmd.Parameters.Add(p);
            cmd.ExecuteNonQuery();
            dr = cmd.ExecuteReader();
            dr.Read();
            buff = (byte[])dr[0];


            byte[] buff1 = new byte[buff.Length + 1];
            buff1[0] = 1;
            Buffer.BlockCopy(buff, 0, buff1, 1, buff.Length);


            dr.Close();
            cmd.Dispose();
            conn.Close();


            string strKey = "";
            strKey = lbOnline.Text.Trim();
            if (string.IsNullOrEmpty(strKey))   // 判断是不是选择了发送的对象; 
            {
                MessageBox.Show("请选择你要发送的好友!!!");
            }
            else
            {
                dict[strKey].Send(buff1);// 解决了 sokConnection是局部变量,不能再本函数中引用的问题; 
                textBox1.Text = "发送消息成功!" + "\r\n";


            } 


            //string strMsg = "服务器" + "\r\n" + "   -->" + "\r\n";
            //byte[] arrMsg = System.Text.Encoding.Default.GetBytes(strMsg); // 将要发送的字符串转换成Utf-8字节数组; 
            //byte[] arrSendMsg = new byte[arrMsg.Length + 1];
            //arrSendMsg[0] = 0; // 表示发送的是消息数据 
            //Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);
            //string strKey = "";
            //strKey = lbOnline.Text.Trim();
            //if (string.IsNullOrEmpty(strKey))   // 判断是不是选择了发送的对象; 
            //{
            //    MessageBox.Show("请选择你要发送的好友!!!");
            //}
            //else
            //{
            //    dict[strKey].Send(arrSendMsg);// 解决了 sokConnection是局部变量,不能再本函数中引用的问题; 
            //    textBox1.Text = "发送消息成功!" + "\r\n";
            //} 


        }


    }
}


Unity3D客户端:


using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Net.Sockets;
using System.IO;
using UnityEngine.UI;
using System.Net;
using System.Threading;
using System.Linq;




public class KeHuDuan : MonoBehaviour
{
    [SerializeField]
    private Image image0;


    Socket socketClient = null;
    Thread threadClient = null;


    void Start()
    {
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        IPEndPoint endPoint = new IPEndPoint(ip, 8080);
        socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            Debug.Log("与服务器连接中......");
            socketClient.Connect(endPoint);
        }
        catch(SocketException e)
        {
            Debug.Log(e.Message);
            return;
        }
        Debug.Log("与服务器连接成功!");
        threadClient = new Thread(RecMsg);
        threadClient.IsBackground = true;
        threadClient.Start();
    }
    byte[] buff = null;
    private bool chuan = false;
    void Update()
    {
        if (chuan)
        {
            Texture2D texture = new Texture2D(100, 100);
            texture.LoadImage(buff);
            Sprite spr = null;
            spr = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            image0.sprite = spr;
            Debug.Log(buff.Length);
            chuan = false;
        }
    }


    void RecMsg()
    {
        while (true)
        {
            byte[] arrMsg = new byte[1024 * 1024 * 2];
            int length = -1;
            try
            {
                length = socketClient.Receive(arrMsg);//接收到数据,并返回长度
            }
            catch (SocketException e)
            {
                Debug.Log(e.Message);
                return;
            }
            if (arrMsg[0] == 0)//表示接收到的是消息数据
            {
                string strMsg = System.Text.Encoding.Default.GetString(arrMsg, 1, length - 1);//
                Debug.Log("从服务端接收到的数据:" + strMsg);
            }
            if (arrMsg[0] == 1) //表示接收到的是文件数据
            {
                try
                {
                    
                    buff = new byte[length -1];
                    Buffer.BlockCopy(arrMsg, 1, buff, 0, length - 1);
                    chuan = true;
                }
                catch (Exception e)
                {
                    Debug.Log(e.Message);
                }
            }
        }
    }


    void OnApplicationQuit()
    {
        socketClient.Close();
    }


}

 

猜你喜欢

转载自blog.csdn.net/q510264505/article/details/69666987