Я пытаюсь преобразовать существующий код консольного приложения C # в winform C #, приведенный ниже код работает хорошо.
class Program
{
const int PORT_NO = 49211;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
Но когда я пытался преобразовать это в приложение winform, приложение зависает, пока яостановитесь вручную в Visual Studio.Я вложил его в событие нажатия кнопки.
const int PORT_NO = 49211;
const string SERVER_IP = "127.0.0.1";
private void button1_Click(object sender, EventArgs e)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
lstProgress.Items.Add("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
lstProgress.Items.Add("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
client.Close();
}
Любое предложение было бы здорово, спасибо заранее!