我有一个Windows窗体,在与tcpclient建立连接之前无法正常工作。然后它不能正常工作(它会像冻结一样挂起)。
这是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");
}
}
}
}
这是TCP客户端的代码(这个工作正常):
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"); ;
}
}
}
}
对于我能够推断出来的事实,一旦它出现它挂起似乎与计时器有关,但同样的计时器在TCP客户端中工作。
我真的迷失了,我想知道我犯了什么错误以及为什么。 任何人都可以帮助我理解它为什么不起作用吗?
答案 0 :(得分:0)
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();
}
}
}
}
此代码正常运行。问题在于计时器。