Chilkat сокет не отправить строку - PullRequest
0 голосов
/ 07 июня 2019

Я создаю перенаправление данных сокета с помощью библиотеки Chilkat, я могу подключить клиента к серверу сокетов, но, когда я запускаю программу, которая отправляет данные, которые должны быть перенаправлены на подключенный клиент, я получил ошибкуиз чилката либ.говоря, что соединение не установлено (клиенту).

Тестовый код моего сервера:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CallSocketTest
{
    public class TestSocket
    {
        public Dictionary<string, ConnectionManager> Connections { get; set; } = new Dictionary<string, ConnectionManager>();

        public TestSocket(){}

        public void StartConnectionHandler()
        {
            Thread th = new Thread(() =>
            {
                FooSocket listeningSocket = new FooSocket();
                listeningSocket.BindAndListen(5000, 300);

                while (true)
                {
                    FooSocket connectedSocket = listeningSocket.AcceptNextConnection(0);
                    var connection = new ConnectionManager(this, connectedSocket);

                    string connectionKey = "";
                    do
                    {
                        connectionKey = Guid.NewGuid().ToString();
                        if (!Connections.ContainsKey(connectionKey))
                            break;
                    } while (true);

                    Connections[connectionKey] = connection;
                    Connections[connectionKey].StartReadFromClient();

                    Console.WriteLine("CONN: {0}", connectionKey);
                }
            });
            th.Start();
        }
    }

    public class ConnectionManager
    {
        private FooSocket Socket { get; set; }
        private TestSocket SocketTest { get; set; }

        public ConnectionManager(TestSocket testSocket, FooSocket fooSocket)
        {
            Socket = fooSocket;
            SocketTest = testSocket;
        }

        public void StartReadFromClient()
        {
            Thread th = new Thread(() => ReadMessageFromClient());
            th.Start();
        }

        private void ReadMessageFromClient()
        {
            do
            {
                if (!Socket.IsConnected)
                    break;

                var dataRead = Socket.ReadString();
                if (dataRead.Trim().Length == 0)
                    continue;

                // <guid>|<Message>
                var dataSplt = dataRead.Split('|');

                SocketTest.Connections[dataSplt[0]].Socket.SendString(dataSplt[1]);
            } while (true);

            Socket.CloseConnection();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            TestSocket cnn = new TestSocket();
            cnn.StartConnectionHandler();

            while (true)
                Thread.Sleep(1000);
        }
    }
}

Класс сокета Foo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace CallSocketTest
{
    public class FooSocket
    {
        private Chilkat.Socket CkSocket { get; set; }
        private const int SendReceiveBufferSize = 4096 * 256; // 1mb;

        public FooSocket()
        {
            CkSocket = new Chilkat.Socket();
            CkSocket.UnlockComponent("<MY SECRET KEY>");
            SetConnectionDefaults();
        }

        private FooSocket(Chilkat.Socket ckSocket)
        {
            this.CkSocket = ckSocket;
            SetConnectionDefaults();
        }

        private void SetConnectionDefaults()
        {
            if (CkSocket != null)
            {
                CkSocket.KeepAlive = true;
                CkSocket.MaxReadIdleMs = 0;
                CkSocket.MaxSendIdleMs = 0;
                CkSocket.SoSndBuf = SendReceiveBufferSize;
                CkSocket.SoRcvBuf = SendReceiveBufferSize;
            }
        }

        public bool OpenConnection(string ip, int port)
        {
            return OpenConnection(ip, port, false);
        }

        public bool OpenConnection(string ip, int port, bool useSSL)
        {
            return CkSocket.Connect(ip, port, useSSL, 20000);
        }

        public bool BindAndListen(int port, int backLog)
        {
            if (CkSocket.BindAndListen(port, backLog) != true)
                throw new Exception(CkSocket.LastErrorText);

            return true;
        }

        public bool IsConnected
        {
            get
            {
                if (CkSocket == null)
                    return false;

                return CkSocket.IsConnected;
            }
        }

        public void CloseConnection()
        {
            if (CkSocket != null)
            {
                CkSocket.AbortCurrent = true;
                CkSocket.Close(2000);
                CkSocket.Dispose();
                CkSocket = null;
            }
        }

        public FooSocket AcceptNextConnection(int timeOut)
        {
            Chilkat.Socket connectedSocket = CkSocket.AcceptNextConnection(0);
            if (CkSocket.LastMethodSuccess == false)
                throw new Exception(CkSocket.LastErrorText);

            return new FooSocket(connectedSocket);
        }

        public void SendString(string message)
        {
            bool success = CkSocket.SendString(message);
            if (success != true)
            {
                Console.WriteLine(CkSocket.LastErrorText);
                return;
            }
        }

        public byte[] ReadBytes()
        {
            List<byte> bytes = new List<byte>();
            do
            {
                bytes.AddRange(CkSocket.ReceiveBytes());
            } while (CkSocket.PollDataAvailable());
            return bytes.ToArray();
        }

        public string ReadString()
        {
            StringBuilder sb = new StringBuilder();
            do
            {
                sb.Append(CkSocket.ReceiveString());
            } while (CkSocket.PollDataAvailable());

            return sb.ToString();
        }

        public Int16 ReadInt16(bool unsigned, bool bigEndian = true)
        {
            if (!CkSocket.ReceiveInt16(bigEndian, unsigned))
                throw new Exception("Falha ao obter o valor Int32 do cliente");
            return (Int16)CkSocket.ReceivedInt;
        }

        public Int32 ReadInt32()
        {
            return ReadInt32(true);
        }

        public Int32 ReadInt32(bool bigEndian)
        {
            if (!CkSocket.ReceiveInt32(bigEndian))
                throw new Exception("Falha ao obter o valor Int32 do cliente");
            return CkSocket.ReceivedInt;
        }

        public byte ReadByte(bool isUnsigned)
        {
            if (!CkSocket.ReceiveByte(isUnsigned))
                throw new Exception("Falha ao obter o byte do cliente");
            return (byte)CkSocket.ReceivedInt;
        }
    }
}
...