블로그 이미지
따시쿵

calendar

1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Notice

2015. 4. 22. 15:50 C#

데이타베이스 작업을 할시에 필요한 라이브러리를 소개합니다.

select, update, delete, insert 모두에 사용되며, ad-hoc 쿼리나 스토어프로시저 모두에 사용 가능합니다.


사용하는 방법

아래 예제는 모두 Contacts class 가 있어서, UI 버튼 클릭시 Contacts 클래스의 property 에 개별적인 값을 대입한 후, 필요한 작업을 수행합니다.

Contacts.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using DataGridViewExample.lib;

namespace DataGridViewExample.data
{
    public class Contacts
    {
        #region Properties
        public int Idx { get; set; }
        public string Name { get; set; }
        public string BirthInfo { get; set; }
        public string ZipCode { get; set; }
        #endregion

        #region Functions
        /// 
        // Add the contacts info
        /// 
        /// 
        public bool AddContacts()
        {
            bool retval = false;
            try
            { 
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"insert into [dbo].[tbl_contacts](Name, BirthInfo, ZipCode)
                                    values(@Name, @BirthInfo, @ZipCode);";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Name", Name),
                                        new SqlParameter("@BirthInfo", BirthInfo),
                                        new SqlParameter("@ZipCode", ZipCode)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }

        /// 
        /// Modify the contacts info
        /// 
        /// 
        public bool ModifyContacts()
        {
            bool retval = false;
            try
            {
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"update [dbo].[tbl_contacts]
                                set  Name = @Name, BirthInfo = @BirthInfo, ZipCode = @ZipCode
                                where Id = @Idx;";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Name", Name),
                                        new SqlParameter("@BirthInfo", BirthInfo),
                                        new SqlParameter("@ZipCode", ZipCode),
                                        new SqlParameter("@Idx", Idx)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }

        public bool RemoveContacts()
        {
            bool retval = false;
            try
            {
                SQLOperator sdo = new SQLOperator("SampleDBConnectionString");

                string query = @"delete from [dbo].[tbl_contacts]
                                where Id = @Idx;";

                sdo.ExecuteNoneQuery(query,
                                    new SqlParameter[]
                                    {
                                        new SqlParameter("@Idx", Idx)
                                    },
                                    CommandType.Text);
                sdo.Dispose();

                retval = true;
            }
            catch (SqlException se)
            {
                Trace.WriteLine(se.Message);
                retval = false;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
                retval = false;
            }

            return retval;
        }
        #endregion
    }
}


1. select 시


DataTable set 을 가져와서 DataGridView 의 DataSource 에 바인드 합니다.

            SQLOperator sdo = new SQLOperator("SampleDBConnectionString");
            DataTable dt = sdo.ExecuteQuery("select Id, Name, BirthInfo, ZipCode from [dbo].[tbl_contacts]");

            dataGridView1.DataSource = dt;

            dt.Dispose();
            sdo.Dispose();

DataTable set 을 가져와서 List에 넣는 후 DataGridView 의 DataSource 에 바인드 합니다.

            SQLOperator sdo = new SQLOperator("SampleDBConnectionString");
            DataTable dt = sdo.ExecuteQuery("select Id, Name, BirthInfo, ZipCode from [dbo].[tbl_contacts]");

            List<Contacts>  pContact = new List<Contacts>();
            if(dt.Rows.Count > 0)
            {
                foreach(DataRow row in dt.Rows)
                {
                    pContact.Add(new Contacts()
                        {
                            Idx = Convert.ToInt32(row["Id"]),
                            Name = row["Name"].ToString(),
                            BirthInfo = row["BirthInfo"].ToString(),
                            ZipCode = row["ZipCode"].ToString()
                        });
                }
            }

            dataGridView1.DataSource = pContact;

            dt.Dispose();
            sdo.Dispose();


2. update 시

            Contacts contact = new Contacts();

            contact.Idx = Convert.ToInt32(lblIdx.Text);
            contact.Name = txtName.Text.Trim();
            contact.BirthInfo = txtBirthInfo.Text.Trim();
            contact.ZipCode = txtZipCode.Text.Trim();

            if (contact.ModifyContacts())
            {
                toolStripStatusLabel1.Text = Properties.Resources.AddConfirmMsg;
            }
            else
            {
                toolStripStatusLabel1.Text = Properties.Resources.AddErrorMsg;
            }


3. delete 시

            Contacts contact = new Contacts();

            contact.Idx = Convert.ToInt32(lblIdx.Text);
            string message = string.Format("[{0}] 정보를 삭제하시겠습니까", txtName.Text.Trim());

            if (MessageBox.Show(message, "확인", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            { 
                if (contact.RemoveContacts())
                {
                    toolStripStatusLabel1.Text = Properties.Resources.RemoveConfirmMsg;
                }
                else
                {
                    toolStripStatusLabel1.Text = Properties.Resources.RemoveErrorMsg;
                }
            }



4. insert 시

            Contacts contact = new Contacts();

            contact.Name = txtName.Text.Trim();
            contact.BirthInfo = txtBirthInfo.Text.Trim();
            contact.ZipCode = txtZipCode.Text.Trim();

            if (contact.AddContacts())
            {
                toolStripStatusLabel1.Text = Properties.Resources.AddConfirmMsg;
            }
            else 
            { 
                toolStripStatusLabel1.Text = Properties.Resources.AddErrorMsg;
            }




데이타베이스 라이브러리는 아래와 같습니다.

SQLOperator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DataGridViewExample.lib
{
    /// 


/// Summary description for SqlDataOperator /// public class SQLOperator : IDisposable { private SqlConnection conn; private SqlCommand comm; private SqlDataAdapter adap; private SqlTransaction tran; public SqlConnection Connection { get { return conn; } set { conn = value; } } public SqlCommand Command { get { return comm; } set { comm = value; } } public SqlTransaction Transaction { get { return tran; } } public SQLOperator() : this("default") { } public SQLOperator(string connectionStringName) { conn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString); //conn = new SqlConnection(Properties.Settings.Default.SampleDBConnectionString); comm = new SqlCommand(); comm.Connection = conn; adap = new SqlDataAdapter(); } public SqlTransaction BeginTransaction() { if (conn.State == ConnectionState.Closed) conn.Open(); tran = conn.BeginTransaction(); return tran; } public void RollBackTran() { if (tran != null) tran.Rollback(); } public void CommitTran() { if (tran != null) tran.Commit(); } public SqlDataReader ExecuteReader(string query, SqlParameter[] parameters, CommandType commType) { comm.CommandType = commType; comm.CommandText = query; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection); return dr; } public SqlDataReader ExecuteReader(string spName, SqlParameter[] parameters) { comm.CommandType = CommandType.StoredProcedure; comm.CommandText = spName; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection); return dr; } public SqlDataReader ExecuteReader(string query) { comm.CommandType = CommandType.Text; comm.CommandText = query; if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader dr = comm.ExecuteReader(CommandBehavior.CloseConnection); return dr; } public object ExecuteScalar(string sql) { comm.CommandText = sql; comm.CommandType = CommandType.Text; if (conn.State == ConnectionState.Closed) conn.Open(); object result = comm.ExecuteScalar(); comm.Parameters.Clear(); return result; } public object ExecuteScalar(string spName, SqlParameter[] parameters) { comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); object result = comm.ExecuteScalar(); comm.Parameters.Clear(); return result; } public object ExecuteScalar(string spName, SqlParameter[] parameters, CommandType commType) { comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); if (conn.State == ConnectionState.Closed) conn.Open(); object result = comm.ExecuteScalar(); comm.Parameters.Clear(); return result; } public object ExecuteScalar(string spName, SqlParameter[] parameters, CommandType commType, SqlTransaction tran) { comm.Transaction = tran; return ExecuteScalar(spName, parameters, commType); } public object ExecuteScalar(string spName, SqlParameter[] parameters, SqlTransaction tran) { comm.Transaction = tran; return ExecuteScalar(spName, parameters); } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters) { comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); SqlParameter para = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); para.Direction = ParameterDirection.ReturnValue; comm.Parameters.Add(para); if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); comm.Parameters.Clear(); } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters, CommandType commType) { comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); SqlParameter para = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); para.Direction = ParameterDirection.ReturnValue; comm.Parameters.Add(para); if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); comm.Parameters.Clear(); } public int ExecuteNoneQuery_Retrun_Param(string spName, SqlParameter[] parameters, CommandType commType) { comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); SqlParameter para = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); para.Direction = ParameterDirection.ReturnValue; SqlParameter return_param = comm.Parameters.Add(para); if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); var return_param_1 = return_param.Value; comm.Parameters.Clear(); return (int)return_param_1; } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters, CommandType commType, SqlTransaction tran) { comm.Transaction = tran; ExecuteNoneQuery(spName, parameters, commType); } public void ExecuteNoneQuery(string spName, SqlParameter[] parameters, SqlTransaction tran) { comm.Transaction = tran; ExecuteNoneQuery(spName, parameters); } public void ExecuteNoneQuery(string sql, SqlTransaction tran) { comm.Transaction = tran; ExecuteNoneQuery(sql); } public void ExecuteNoneQuery(string sql) { comm.CommandText = sql; comm.CommandType = CommandType.Text; if (conn.State == ConnectionState.Closed) conn.Open(); comm.ExecuteNonQuery(); } public DataTable ExecuteQuery(string tableName, string spName, SqlParameter[] parameters) { DataTable dtResult = new DataTable(tableName); comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dtResult); comm.Parameters.Clear(); return dtResult; } public DataTable ExecuteQuery(string tableName, string spName, SqlParameter[] parameters, CommandType commType) { DataTable dtResult = new DataTable(tableName); comm.CommandText = spName; comm.CommandType = commType; AddParameters(parameters); adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dtResult); comm.Parameters.Clear(); return dtResult; } public DataSet ExecuteQueryToDS(string spName, SqlParameter[] parameters) { DataSet dsResult = new DataSet(); comm.CommandText = spName; comm.CommandType = CommandType.StoredProcedure; AddParameters(parameters); adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dsResult); comm.Parameters.Clear(); return dsResult; } public DataTable ExecuteQuery(string tableName, string sql) { DataTable dtResult = ExecuteQuery(sql); dtResult.TableName = tableName; return dtResult; } public DataTable ExecuteQuery(string sql) { DataTable dtResult = new DataTable(); comm.CommandText = sql; comm.CommandType = CommandType.Text; adap.SelectCommand = comm; if (conn.State == ConnectionState.Closed) conn.Open(); adap.Fill(dtResult); return dtResult; } private void AddParameters(SqlParameter[] parameters) { comm.Parameters.Clear(); foreach (SqlParameter parameter in parameters) { comm.Parameters.Add(parameter); } } public string AntiInjection(string val) { val = RemoveScriptTag(val).Replace("'", "''"); return val; } public static string RemoveScriptTag(string s) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("(?<capture><[/]?script[a-zA-Z_0-9=\"\'\\s]*>)"); System.Text.RegularExpressions.MatchEvaluator evaluator = new System.Text.RegularExpressions.MatchEvaluator(MatchReplace); return reg.Replace(s, evaluator); } public static string MatchReplace(System.Text.RegularExpressions.Match m) { string s = m.Groups["capture"].Value; s = s.Replace("<", "<").Replace(">", ">"); return s; } #region IDisposable 멤버 public void Dispose() { comm.Parameters.Clear(); if (conn.State == ConnectionState.Open) conn.Close(); } #endregion } }

'C#' 카테고리의 다른 글

로그인 창  (0) 2015.05.08
멀티플(multiple) 윈도우 - 2  (0) 2015.05.07
BackgroundWorker class  (0) 2015.03.02
텍스트 로그 파일 라이브러리 - 3  (0) 2015.02.21
텍스트 로그 파일 라이브러리 - 2  (0) 2015.02.21
posted by 따시쿵
2015. 4. 2. 14:42 C# with TCP/IP

프로그램 설명


텍스트와 이미지 파일을 전송하는 예제입니다.

규칙은 아래 그림과 같습니다.



실행 후



연결 후



텍스트 전송 후



이미지 파일 전송 후




프로그램 작성 순서


1. 서버 프로그램

전체 소스는 아래에 있으며, 핵심적인 내용의 소스만 갈무리해서 올립니다.

AsyncSocketServer.zip

        public void ReceiveAsync()
        {
            socket.BeginReceive(lenBuffer, 0, lenBuffer.Length, SocketFlags.None, receiveCallBack, null);
        }

        public void receiveCallBack(IAsyncResult ar)
        {
            try
            {
                int rec = socket.EndReceive(ar);

                if (rec == 0)
                {
                    if (Disconnected != null)
                    {
                        Disconnected(this);
                        return;
                    }
                }

                if (rec != 4)
                {
                    throw new Exception();
                }
            }
            catch(SocketException se)
            {
                switch(se.SocketErrorCode)
                {
                    case SocketError.ConnectionAborted:
                    case SocketError.ConnectionReset:
                        if (Disconnected != null)
                        {
                            Disconnected(this);
                            return;
                        }
                        break;
                }
            }
            catch(ObjectDisposedException)
            {
                return;
            }
            catch(NullReferenceException)
            {
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            buffer = new ReceiveBuffer(BitConverter.ToInt32(lenBuffer, 0));

            socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallBack, null);
        }

        public void receivePacketCallBack(IAsyncResult ar)
        {
            int rec = socket.EndReceive(ar);

            if (rec <= 0)
            {
                return;
            }

            buffer.BufStream.Write(buffer.Buffer, 0, rec);

            buffer.ToReceive -= rec;

            if (buffer.ToReceive > 0)
            {
                Array.Clear(buffer.Buffer, 0, buffer.Buffer.Length);

                socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallBack, null);
                return;
            }

            if (DataReceived != null)
            {
                buffer.BufStream.Position = 0;
                DataReceived(this, buffer);
            }

            buffer.Dispose();

            ReceiveAsync();
        }


2. 클라이언트 프로그램

전체 소스는 아래에 있으며, 핵심적인 내용의 소스만 갈무리해서 올립니다.


AsyncSocketClient.zip

        void SendText(string text)
        {
            BinaryWriter bw = new BinaryWriter(new MemoryStream());
            bw.Write((int)Commands.String);
            bw.Write(text);
            byte[] data = ((MemoryStream)bw.BaseStream).ToArray();
            bw.BaseStream.Dispose();
            client.Send(data, 0, data.Length);
            data = null;
        }

        void SendImage(string path)
        {
            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            byte[] b = File.ReadAllBytes(path);
            bw.Write((int)Commands.Image);
            bw.Write((int)b.Length);
            bw.Write(b);
            bw.Close();
            b = ms.ToArray();
            ms.Dispose();

            client.Send(b, 0, b.Length);
        }
posted by 따시쿵
2015. 3. 26. 13:45 C# with TCP/IP

프로그램 설명


바이트 배열을 이용한 파일 전송을 구현한 예시입니다.

이미지 파일 전송시 데이타 구조와 일반 텍스트 데이타 구조가 다르므로 아래에 그림으로 표시했습니다.

실행 후




이미지 파일 전송 후



메시지 전송 후




프로그램 작성


1. 데이타 버퍼 클래스 (StateObject.cs)


    class StateObject
    {
        // Client socket
        public Socket workSocket = null;

        public const int BufferSize = 4096;

        // Receive buffer
        public byte[] buffer = new byte[BufferSize];
    }


2. 서버 프로그램


    public partial class MainForm : Form
    {
        bool initialFlag = true;
        string receivedPath = string.Empty;
        enum DataPacketType { TEXT = 1, IMAGE };
        int dataType = 0;
        string textData = string.Empty;

        public MainForm()
        {
            InitializeComponent();

            Thread t_handler = new Thread(StartListening);
            t_handler.IsBackground = true;
            t_handler.Start();
        }

        public static ManualResetEvent allDone = new ManualResetEvent(false);
        private void StartListening()
        {
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEP);
                listener.Listen(10);

                while(true)
                {
                    allDone.Reset();
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                    allDone.WaitOne();
                }
            }
            catch(SocketException se)
            {
                Trace.WriteLine(string.Format("SocketException :{0}", se.Message));
            }
            catch(Exception ex)
            {
                Trace.WriteLine(string.Format("Exception :{0}", ex.Message));
            }
        }

        private void AcceptCallback(IAsyncResult ar)
        {
            allDone.Set();

            Socket listener = ar.AsyncState as Socket;
            Socket handler = listener.EndAccept(ar);

            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
            initialFlag = true;
        }

        private void ReadCallback(IAsyncResult ar)
        {
            int fileNameLen = 0;
            string content = string.Empty;
            StateObject state = ar.AsyncState as StateObject;
            Socket handler = state.workSocket;
            int bytesRead = handler.EndReceive(ar);
            
            if(bytesRead > 0)
            {                
                if (initialFlag)
                {
                    dataType = BitConverter.ToInt32(state.buffer, 0);
                    if (dataType == (int)DataPacketType.IMAGE)
                    { 
                        fileNameLen = BitConverter.ToInt32(state.buffer, 4);
                        string fileName = Encoding.UTF8.GetString(state.buffer, 8, fileNameLen);

                        string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                        string pathDownload = Path.Combine(pathUser, "Downloads");

                        receivedPath = Path.Combine(pathDownload, fileName);

                        if (File.Exists(receivedPath))
                            File.Delete(receivedPath);
                    }
                    else if (dataType == (int)DataPacketType.TEXT)
                    {
                        textData = Encoding.UTF8.GetString(state.buffer, 4, bytesRead - 4);
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    }
                }

                if (dataType == (int)DataPacketType.IMAGE)
                {
                    BinaryWriter bw = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                    if (initialFlag)
                        bw.Write(state.buffer, 8 + fileNameLen, bytesRead - (8 + fileNameLen));
                    else
                        bw.Write(state.buffer, 0, bytesRead);

                    initialFlag = false;
                    bw.Close();
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
            }
            else
            {
                if (dataType == (int)DataPacketType.IMAGE)
                {
                    pictureBox1.ImageLocation = receivedPath;
                    Invoke((MethodInvoker)delegate
                    {
                        lblMessage.Text = "Data has been received";
                    });
                }
                else if (dataType == (int)DataPacketType.TEXT)
                    Invoke((MethodInvoker)delegate
                    {
                        textBox1.AppendText(textData + Environment.NewLine);
                    });
            }
        }
    }


3. 클라이언트 프로그램


    public partial class MainForm : Form
    {
        string m_splitter = "'\\'";
        string m_fName = string.Empty;
        string[] m_split = null;
        byte[] m_clientData = null;
        enum DataPacketType { TEXT = 1, IMAGE };

        public MainForm()
        {
            InitializeComponent();
            
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            char[] delimeter = m_splitter.ToCharArray();

            openFileDialog1.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;
            pictureBox1.ImageLocation = openFileDialog1.FileName;

            m_split = textBox1.Text.Split(delimeter);
            int limit = m_split.Length;

            m_fName = m_split[limit - 1].ToString();

            if (textBox1.Text != null)
                btnSend.Enabled = true;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            Thread t_handler = new Thread(SendData);
            t_handler.IsBackground = true;
            t_handler.Start();
        }

        private void SendData()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            byte[] fileName = Encoding.UTF8.GetBytes(m_fName);
            byte[] fileData = File.ReadAllBytes(textBox1.Text);
            byte[] fileNameLen = BitConverter.GetBytes(fileName.Length);
            byte[] fileType = BitConverter.GetBytes((int)DataPacketType.IMAGE);
            // IMAGE(4 byte) + 파일이름(4 byte) + 파일이름길이(4 byte) + 데이타 길이
            m_clientData = new byte[fileType.Length + 4 + fileName.Length + fileData.Length];

            fileType.CopyTo(m_clientData, 0);
            fileNameLen.CopyTo(m_clientData, 4);
            fileName.CopyTo(m_clientData, 8);
            fileData.CopyTo(m_clientData, 8 + fileName.Length);
            
            clientSocket.Connect(IPAddress.Parse("192.168.0.11"), 9050);
            clientSocket.Send(m_clientData);
            clientSocket.Close();
        }

        private void btnSendText_Click(object sender, EventArgs e)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            byte[] textData = Encoding.UTF8.GetBytes(textBox2.Text);
            byte[] fileType = BitConverter.GetBytes((int)DataPacketType.TEXT);
            // TEXT(4 byte) + 데이타 길이
            m_clientData = new byte[fileType.Length + textData.Length];

            fileType.CopyTo(m_clientData, 0);
            textData.CopyTo(m_clientData, 4);

            clientSocket.Connect(IPAddress.Parse("192.168.0.11"), 9050);
            clientSocket.Send(m_clientData);
            clientSocket.Close();
        }
    }

posted by 따시쿵