내가만든/라인들2016. 2. 28. 16:25

C++ -> C#

처음에는 C++로 구현했다가 콘솔의 한계.. 로 인해 UI를 위해 C#으로 변경

마샬링이 어려워서 그냥 JSON형식으로 전달. 서버와 마찬가지로 전체 소스는 SVN에!

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using PacketDLL;
using ChatClient_CSharp.Library;
using System.Net.Json;
using System.Windows.Forms;

namespace ChatClient_CSharp
{
    delegate void DText(string strMessage);

    public class ClientInfo
    {
        private IPAddress m_IpAddress;
        private int m_nPort;
        private TcpClient m_ClientSocket;
       
        /* 스트림 전송 관련 */
        private NetworkStream m_NetWorkStream;
        private StreamReader m_strReader;
        private StreamWriter m_strWriter;

        private MemoryStream m_MemStream;
        private BinaryFormatter m_BinaryFomatter;

        private string m_strNickName;

        public ClientInfo()
        {
            m_IpAddress = IPAddress.Parse("127.0.0.1");
            m_nPort = 50001;
            m_strNickName = "";
        }

        public IPAddress IpAddress
        {
            get { return this.m_IpAddress; }
            set { this.m_IpAddress = value; }
        }
        public int Port       
        {
            get { return this.m_nPort; }
            set { this.m_nPort = value; }
        }

        public TcpClient MyClientSocket
        {
            get { return this.m_ClientSocket; }
            set { this.m_ClientSocket = value; }
        }

        public NetworkStream MyNetWorkStream
        {
            get { return this.m_NetWorkStream; }
            set { this.m_NetWorkStream = value; }
        }
        public StreamReader MyStreamReader
        {
            get { return this.m_strReader; }
            set { this.m_strReader = value; }
        }
        public StreamWriter MyStreamWriter
        {
            get { return this.m_strWriter; }
            set { this.m_strWriter = value; }
        }
        public string NickName
        {
            get { return this.m_strNickName; }
            set { this.m_strNickName = value; }
        }
        public MemoryStream MyMemoryStream
        {
            get { return this.m_MemStream; }
            set { this.m_MemStream = value; }
        }
        public BinaryFormatter MyBinaryFomatter
        {
            get { return this.m_BinaryFomatter; }
            set { this.m_BinaryFomatter = value; }
        }
    }
    public class Client : Library.Singleton.MySingleton<Client>
    {
        public const int BUFFER_SIZE = 4096;

        private AsyncCallback asReceiveThread;
        private AsyncCallback asSendThread;
        private System.Windows.Forms.TextBox textBox_Chat;
        private ClientInfo ClientInfo;
        private DText call;

        public ClientInfo CInfo
        {
            get { return this.ClientInfo; }
        }

        public Client()
        {
            Init();
            //ConnectToServer();
        }

        private void Init()
        {
            ClientInfo = new ClientInfo();
            call       = new DText(Print_Text);
        }

        public bool ConnectToServer()
        {
            ClientInfo.MyClientSocket = new TcpClient();
            IPEndPoint EP = new IPEndPoint(ClientInfo.IpAddress, ClientInfo.Port);

            int nTryCnt = 0;
            while (true)
            {
                try
                {
                    ClientInfo.MyClientSocket.Connect(EP);
                    break;
                }
                catch
                {
                    if (10 < nTryCnt)
                    {
                        return false;
                    }
                    nTryCnt++;
                }
            }

            ClientInfo.MyNetWorkStream = ClientInfo.MyClientSocket.GetStream();
            ClientInfo.MyClientSocket.ReceiveBufferSize = BUFFER_SIZE;
            ClientInfo.MyClientSocket.SendBufferSize = BUFFER_SIZE;

            this.CreateReceiveThread();

            return true;
        }

        public void CreateReceiveThread()
        {
            Thread ThreadHandle = new Thread(new ThreadStart(Receive_Thread));
            ThreadHandle.Start();

            ClientInfo.MyStreamReader = new StreamReader(ClientInfo.MyNetWorkStream);
            ClientInfo.MyStreamWriter = new StreamWriter(ClientInfo.MyNetWorkStream);
        }
       
        public void SendMessage(string strMessage)
        {
            string strName = "["+ MyForm.MainForm.GetNameBox().Text +"] ";

            JsonObjectCollection JsonCollection = new JsonObjectCollection();
            JsonCollection.Add(new JsonStringValue("Nick", strName));
            JsonCollection.Add(new JsonStringValue("Chat", strMessage));
            string strSendMessage = JsonCollection.ToString();

            byte[] ByteMessage = System.Text.Encoding.Default.GetBytes(strSendMessage.ToCharArray());
            ClientInfo.MyNetWorkStream.Write(ByteMessage, 0, ByteMessage.Length);
            ClientInfo.MyNetWorkStream.Flush();
        }

        private void Receive_Thread()
        {
            byte[] byteMessage = new byte[BUFFER_SIZE];
            BinaryFormatter BF = new BinaryFormatter();
            NetworkStream stream = ClientInfo.MyNetWorkStream;
           
            while (true)
            {
                try
                {
                    ClientInfo.MyNetWorkStream.Read(byteMessage, 0, byteMessage.Length);
                    MemoryStream MemStream = new MemoryStream(byteMessage);
                   
                    JsonTextParser JsonParser = new JsonTextParser();                   
                    JsonObject     JsonObj    = JsonParser.Parse(Encoding.Default.GetString(byteMessage));
                    JsonObjectCollection JsonCol = (JsonObjectCollection)JsonObj;

                    string Nick = (string)JsonCol["Nick"].GetValue();
                    string Chat = (string)JsonCol["Chat"].GetValue();
                    string StrChat = Nick + Chat;
                    Print_Text( StrChat );
                }
                catch
                {                  
                    break;
                }
            }
        }

        public void SetNickName( string strName )
        {
            if( null == strName || "" == strName )
            {
                return;
            }
            this.ClientInfo.NickName = strName;
        }
        public void Print_Text(string strMessage)
        {
            if (MyForm.MainForm.GetTextBox_Chat().InvokeRequired)
            {
                DText call = new DText(Print_Text);
                MyForm.MainForm.GetTextBox_Chat().Invoke(call, strMessage);
            }
            else
            {
                MyForm.MainForm.GetTextBox_Chat().AppendText(strMessage + "\r\n");
                MyForm.MainForm.FocusToType();
            }           
        }

        public bool IsClientConnected()
        {
            return ClientInfo.MyClientSocket.Connected;
        }

        public void DisconnectFromServer()
        {
            ClientInfo.MyStreamReader.Close();
            ClientInfo.MyStreamWriter.Close();
            ClientInfo.MyNetWorkStream.Close();
            ClientInfo.MyClientSocket.Close();
        }       
    }   
}

Posted by 비엔나햄