मेरे पास एक विंडोज़ फॉर्म है जो तब तक काम नहीं करता जब तक एक टीसीपी क्लाइंट के साथ कनेक्शन नहीं बनाया जाता है। और फिर यह ठीक से काम नहीं करता है (यह फ्रीज की तरह लटका रहता है)।

यह TCPListener के लिए कोड है:

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace ServerChatGUI
{
public partial class Form1 : Form
{
    public Timer timer1;
    public TcpListener myList = null;

    public string EncryptionKey = GetHashedKey("Alexandros");

    public Form1()
    {
        InitializeComponent();
        try
        {
            IPAddress ipAd = IPAddress.Parse("172.17.1.241");
            // use local m/c IP address, and 
            // use the same in the client

            /* Initializes the Listener */
            myList = new TcpListener(ipAd, 8001);

            /* Start Listeneting at the specified port */
            myList.Start();


            Socket s = myList.AcceptSocket();
            this.Show();

            chatDisplay_txtbox.AppendText("Connection accepted from " + s.RemoteEndPoint + "\n");
            connection_lbl.Text = "Connected";
            connection_lbl.ForeColor = Color.Green;


            //InitTimer();
        }

        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.ToString());
        }


    }

    public static string GetHashedKey(string text)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        int cntr = 0;
        foreach (byte x in hash)
        {
            if (cntr == 1)
            {
                cntr = 0;
            }
            else
            {
                hashString += String.Format("{0:x2}", x);
                cntr++;
            }
        }
        return hashString;
    }

    //Encrypting a string
    public static string TxtEncrypt(string inText, string key)
    {
        byte[] bytesBuff = Encoding.UTF8.GetBytes(inText);
        using (Aes aes = Aes.Create())
        {
            Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            aes.Key = crypto.GetBytes(32);
            aes.IV = crypto.GetBytes(16);
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(bytesBuff, 0, bytesBuff.Length);
                    cStream.Close();
                }
                inText = Convert.ToBase64String(mStream.ToArray());
            }
        }
        return inText;
    }

    //Decrypting a string
    public static string TxtDecrypt(string cryptTxt, string key)
    {
        cryptTxt = cryptTxt.Replace(" ", "+");
        cryptTxt = cryptTxt.Replace("\0", "");
        byte[] bytesBuff = Convert.FromBase64String(cryptTxt);
        using (Aes aes = Aes.Create())
        {
            Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            aes.Key = crypto.GetBytes(32);
            aes.IV = crypto.GetBytes(16);
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(bytesBuff, 0, bytesBuff.Length);
                    cStream.Close();
                }
                cryptTxt = Encoding.UTF8.GetString(mStream.ToArray());
            }
        }
        return cryptTxt;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        Socket s = myList.AcceptSocket();
        chatDisplay_txtbox.AppendText("Me:\t ");
        chatDisplay_txtbox.AppendText(inMessage_txtbox.Text + "\n");


        String str = TxtEncrypt(inMessage_txtbox.Text, EncryptionKey);
        s.Send(Encoding.UTF8.GetBytes(str));

    }

    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 200; // in miliseconds
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Socket s = myList.AcceptSocket();
        if (s.Available > 0)
        {
            byte[] b = new byte[s.ReceiveBufferSize];
            int k = s.Receive(b);
            string msg = "";
            chatDisplay_txtbox.AppendText("Other:\t");
            for (int i = 0; i < k; i++)
            {
                msg += Convert.ToChar(b[i]);
            }
            chatDisplay_txtbox.AppendText(TxtDecrypt(msg, EncryptionKey) + "\n");
        }
    }
}
}

और यह टीसीपी क्लाइंट के लिए कोड है (यह काम करता है):

using System;
using System.Drawing;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace ChatClientGUI
{
public partial class Form1 : Form
{
    public string EncryptionKey = GetHashedKey("Alexandros");
    public TcpClient tcpclnt = null;
    public bool cntrl = false;
    public Timer timer1;
    public Form1()
    {
        InitializeComponent();
        try
        {
            tcpclnt = new TcpClient();
            chatDisplayer_txtbox.AppendText("this is the beginning of your chat\n");
            tcpclnt.Connect("172.17.1.241", 8001);
            // use the ipaddress as in the server program



            displayConnection_lbl.Text = "Connected";
            displayConnection_lbl.ForeColor = Color.Green;

            InitTimer();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.ToString());
        }

    }

    public static string GetHashedKey(string text)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        int cntr = 0;
        foreach (byte x in hash)
        {
            if (cntr == 1)
            {
                cntr = 0;
            }
            else
            {
                hashString += String.Format("{0:x2}", x);
                cntr++;
            }
        }
        return hashString;
    }

    //Encrypting a string
    public static string TxtEncrypt(string inText, string key)
    {
        byte[] bytesBuff = Encoding.UTF8.GetBytes(inText);
        using (Aes aes = Aes.Create())
        {
            Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            aes.Key = crypto.GetBytes(32);
            aes.IV = crypto.GetBytes(16);
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(bytesBuff, 0, bytesBuff.Length);
                    cStream.Close();
                }
                inText = Convert.ToBase64String(mStream.ToArray());
            }
        }
        return inText;
    }

    //Decrypting a string
    public static string TxtDecrypt(string cryptTxt, string key)
    {
        cryptTxt = cryptTxt.Replace(" ", "+");
        byte[] bytesBuff = Convert.FromBase64String(cryptTxt);
        using (Aes aes = Aes.Create())
        {
            Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            aes.Key = crypto.GetBytes(32);
            aes.IV = crypto.GetBytes(16);
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(bytesBuff, 0, bytesBuff.Length);
                    cStream.Close();
                }
                cryptTxt = Encoding.UTF8.GetString(mStream.ToArray());
            }
        }
        return cryptTxt;
    }

    private void SendMessage_btn_Click(object sender, EventArgs e)
    {
        chatDisplayer_txtbox.AppendText("Me:\t ");
        chatDisplayer_txtbox.AppendText(inMessage_txtbox.Text + "\n");

        String str = TxtEncrypt(inMessage_txtbox.Text, EncryptionKey);
        Stream stm = tcpclnt.GetStream();

        byte[] ba = Encoding.UTF8.GetBytes(str);

        stm.Write(ba, 0, ba.Length);
        cntrl = true;
    }


    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 200; // in miliseconds
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (tcpclnt.Available > 0)
        {
            Stream stm = tcpclnt.GetStream();

            byte[] bb = new byte[tcpclnt.ReceiveBufferSize];

            int k = stm.Read(bb, 0, tcpclnt.ReceiveBufferSize);
            string msg = "";
            chatDisplayer_txtbox.AppendText("Other:\t");
            for (int i = 0; i < k; i++)
            {
                msg += Convert.ToChar(bb[i]);
            }
            chatDisplayer_txtbox.AppendText(TxtDecrypt(msg, EncryptionKey) + "\n"); ;
        }
    }

}
}

जो मैं निकालने में सक्षम हूं, तथ्य यह है कि एक बार यह लटकने के बाद टाइमर से संबंधित प्रतीत होता है, लेकिन वही टाइमर टीसीपी क्लाइंट में काम करता है।

मैं वास्तव में खो गया हूं और मैं समझना चाहता हूं कि यह कहां है कि मैंने गलती की है और क्यों। क्या कोई मुझे यह समझने में मदद कर सकता है कि यह क्यों काम नहीं करता है?

0
Alex Coronas 2 नवम्बर 2017, 14:46

1 उत्तर

सबसे बढ़िया उत्तर
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace ServerChatGUI
{
public partial class Form1 : Form
{
    public static TcpListener myList = null;
    public static Socket s = null;
    public static string EncryptionKey = GetHashedKey("Alexandros");
    public static TextBox chatBox = null;

    public Form1()
    {
        InitializeComponent();
        try
        {
            chatBox = chatDisplay_txtbox;
            IPAddress ipAd = IPAddress.Parse("192.168.1.12");
            // use local m/c IP address, and
            // use the same in the client

            /* Initializes the Listener */
            myList = new TcpListener(ipAd, 8001);

            /* Start Listeneting at the specified port */
            myList.Start();

            s = myList.AcceptSocket();

            chatDisplay_txtbox.AppendText("Connection accepted from " + s.RemoteEndPoint + "\n");
            connection_lbl.Text = "Connected";
            connection_lbl.ForeColor = Color.Green;

            System.Threading.Timer t = new System.Threading.Timer(TimerCallback, null, 0, 2000);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.ToString());
        }
    }

    public static string GetHashedKey(string text)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        int cntr = 0;
        foreach (byte x in hash)
        {
            if (cntr == 1)
            {
                cntr = 0;
            }
            else
            {
                hashString += String.Format("{0:x2}", x);
                cntr++;
            }
        }
        return hashString;
    }

    //Encrypting a string
    public static string TxtEncrypt(string inText, string key)
    {
        byte[] bytesBuff = Encoding.UTF8.GetBytes(inText);
        using (Aes aes = Aes.Create())
        {
            Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            aes.Key = crypto.GetBytes(32);
            aes.IV = crypto.GetBytes(16);
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(bytesBuff, 0, bytesBuff.Length);
                    cStream.Close();
                }
                inText = Convert.ToBase64String(mStream.ToArray());
            }
        }
        return inText;
    }

    //Decrypting a string
    public static string TxtDecrypt(string cryptTxt, string key)
    {
        cryptTxt = cryptTxt.Replace(" ", "+");
        cryptTxt = cryptTxt.Replace("\0", "");
        byte[] bytesBuff = Convert.FromBase64String(cryptTxt);
        using (Aes aes = Aes.Create())
        {
            Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            aes.Key = crypto.GetBytes(32);
            aes.IV = crypto.GetBytes(16);
            using (MemoryStream mStream = new MemoryStream())
            {
                using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cStream.Write(bytesBuff, 0, bytesBuff.Length);
                    cStream.Close();
                }
                cryptTxt = Encoding.UTF8.GetString(mStream.ToArray());
            }
        }
        return cryptTxt;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        chatDisplay_txtbox.AppendText("Me:\t ");
        chatDisplay_txtbox.AppendText(inMessage_txtbox.Text + "\n");

        String str = TxtEncrypt(inMessage_txtbox.Text, EncryptionKey);
        s.Send(Encoding.UTF8.GetBytes(str));
        GC.Collect();
    }

    private void TimerCallback(Object o)
    {
        if (s.ReceiveBufferSize > 0)
        {
            byte[] b = new byte[s.ReceiveBufferSize];
            int k = s.Receive(b);
            string msg = "";
            chatDisplay_txtbox.Invoke(new Action(() => chatDisplay_txtbox.AppendText("Other:\t")));
            for (int i = 0; i < k; i++)
            {
                msg += Convert.ToChar(b[i]);
            }
            chatDisplay_txtbox.Invoke(new Action(() => chatDisplay_txtbox.AppendText(TxtDecrypt(msg, EncryptionKey) + "\n")));
            GC.Collect();
        }
     }
  }
}

यह कोड, ठीक से काम करता है। समस्या टाइमर में थी।

0
Alex Coronas 2 नवम्बर 2017, 18:04