Как остановить TCP-сервер от другого события в C # - PullRequest
0 голосов
/ 11 сентября 2018

Я нахожусь в начале создания небольшого TCP-сервера.

Теперь я застрял в связи между двумя событиями / функциями. Теперь я могу работать с потоками.

Но как я могу закрыть поток и остановить сервер? Он говорит, что не знает клиента и сервера в событии Button_stop.

Код в «Сервере» - это пример кода от Microsoft, но он работает.


Мой код:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace MTTCP
{
public partial class Form1 : Form
{
    //Declare Thread
    Thread Server_Thread;

    public Form1()
    {
        InitializeComponent();
    }

    private void Start_Click(object sender, EventArgs e)
    {
        //Start Backround Server Thread
        Server_Thread = new Thread(Server);
        Server_Thread.Start();
    }

    //Backround Server
    private void Server()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 80.
            Int32 port = 80;
            IPAddress localAddr = IPAddress.Parse("192.168.0.123");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // 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!");

                data = null;

                // Get a stream object for reading and writing
                NetworkStream stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    //Console.WriteLine("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("Sent: {0}", data);
                }

                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            //Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }
        //Backround Server Ende

    }

    private void Stop_Click(object sender, EventArgs e)
    {
        //Here i want to stop the Thread an determine the Server

        client.Close(); //Does not work, doesnt know client
        server.Stop(); //Does not work, doesnt know server
    }
}
}

С уважением NetflixAndChill

1 Ответ

0 голосов
/ 11 сентября 2018

Кажется, вы получаете сообщение об ошибке «клиент и сервер не существует в текущем контексте».Вы должны изменить область видимости переменных «сервер» и «клиент» на уровень класса, чтобы иметь возможность доступа к ним в обработчике событий Stop_Click.

С уважением, Dileep.

...