Всем привет! Мне нужно создать простое клиент-серверное приложение для обмена сообщениями между сервером и клиентом, по заданному IP. Взял пример из MSDN(код ниже), но он работает только с консолью, а мне нужно использовать форму. Я сделал так, что бы сообщения выводились в ListBox т.е. вместо Console.Write("Waiting for a connection... "); пишу listBox1.Items.Add ("Waiting for a connection... ");, но код работает только до первого while, если while убрать, то до строки TcpClient client = server.AcceptTcpClient(); т.е зависает на ней. Помогите! Что не так?
| Код | using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading;
public class TcpListenerSample {
static void Main(string[] args) { try { // set the TcpListener on port 13000 int port = 13000; TcpListener server = new TcpListener(IPAddress.Any, port);
// Start listening for client requests server.Start();
// Buffer for reading data byte[] bytes = new byte[1024]; string data;
//Enter the listening loop while (true) { Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!");
// Get a stream object for reading and writing NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client. i = stream.Read(bytes, 0, bytes.Length);
while (i != 0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine(String.Format("Received: {0}", data));
// Process the data sent by the client. data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine(String.Format("Sent: {0}", data));
i = stream.Read(bytes, 0, bytes.Length);
}
// Shutdown and end connection client.Close(); } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); }
Console.WriteLine("Hit enter to continue..."); Console.Read(); }
}
|
Похоже здесь происходит зацикливание. Как сделать так, чтобы сервер прослушивал порт, ожидая обращения клиента ? |