C # TCP соединение потеряно - PullRequest
0 голосов
/ 17 ноября 2018

для следующего кода мой клиент делает запрос к серверу, но сразу же, как он делает (после успешного подключения), я получаю эту ошибку «Ошибка сети».Я искал дополнительную информацию об этом с отладчиком, но не повезло.Все это с выключенным межсетевым экраном.

Событие потери соединения дает мне общее сообщение «Ошибка сети».

public class Server
{
    private ServerConnectionContainer serverConnectionContainer;

    public void StartServer()
    {
        Console.WriteLine("Please enter the server port and press return:");
        string port = Console.ReadLine();

        //1. Start listen on a port
        serverConnectionContainer = ConnectionFactory.CreateServerConnectionContainer(int.Parse(port), false);
        serverConnectionContainer.ConnectionLost += (a, b, c) =>
            {
                Console.WriteLine($"{serverConnectionContainer.Count} {b.ToString()} Connection lost {a.IPRemoteEndPoint.Port}. Reason {c.ToString()}");
            };

        serverConnectionContainer.ConnectionEstablished += connectionEstablished;
        serverConnectionContainer.AllowUDPConnections = true;

        serverConnectionContainer.Start();

        Console.WriteLine("Server started");

        while (true) {

        }
    }

    /// <summary>
    /// We got a connection.
    /// </summary>
    /// <param name="connection">The connection we got. (TCP or UDP)</param>
    private void connectionEstablished(Connection connection, ConnectionType type)
    {
        connection.EnableLogging = true;
        connection.LogIntoStream(Console.OpenStandardOutput());

        Console.WriteLine($"{serverConnectionContainer.Count} {connection.GetType()} connected on port {connection.IPRemoteEndPoint.Port}");

        //3. Register packet listeners.
        connection.RegisterPacketHandler<TrainerRequest>(TrainerRequestReceived, this);
    }

    private void TrainerRequestReceived(TrainerRequest req, Connection connection)
    {
        Console.WriteLine($"RawDataPacket received. Data: {string.Join(", ", req.Data["pos_ally"])}");

        var test = new Dictionary<string, byte[]>();
        test.Add("pos_ally", new byte[] { 1, 2, 3, 4 });

        connection.Send(new TrainerResponse(test, req));
    }
}

public class Client
{
    public static async Task StartClient()
    {
        //Request server IP and port number
        Console.WriteLine("Please enter the server IP in the format 192.168.0.1 and press return:");
        string ip = Console.ReadLine();

        Console.WriteLine("Please enter the server port and press return:");
        string port = Console.ReadLine();

        //Parse the necessary information out of the provided string
        ConnectionResult connectionResult = ConnectionResult.TCPConnectionNotAlive;
        //1. Establish a connection to the server.
        TcpConnection tcpConnection = ConnectionFactory.CreateTcpConnection(ip, int.Parse(port), out connectionResult);

        //2. Register what happens if we get a connection
        if (connectionResult == ConnectionResult.Connected)
        {
            Console.WriteLine($"{tcpConnection.ToString()} Connection established");
            //3. Send a raw data packet request.
            tcpConnection.KeepAlive = true;

            while (true)
            {
                var test = new Dictionary<string, byte[]>();
                test.Add("pos_ally", new byte[] { 5, 6, 7, 8 });

                var res = await tcpConnection.SendAsync<TrainerResponse>(new TrainerRequest { Data = test });

                Thread.Sleep(100);
            }
        }
    }
}

1 Ответ

0 голосов
/ 17 ноября 2018

Пока истина блокировала мою нить

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...