1

I really hope this question is not super stupid to ask, but after hours of research without any solution i just had to ask my question here.

Normally im establishing TCP/IP connections to communicate with some local telegramm testing tool/ or PLC Software, so far there never was any need for seperating the sending - and retrieving Channel. (I only use the connection to communicate per strings, normally it looks like this :

(Im always the server, broadcasting my whole network to accept any incoming connection)

standard procedure -Client sends message on Port: 62000 -Server acknowledges message on Port: 62000 -Server awnsers with another message on Port: 62000 -Client acknowledges message on Port: 62000

special procedure (case i need help with) -Client sends message on Port: 62001 -Server acknowledges message on Port: 62001 -Server awnsers with another message on Port: 62000 -Client acknowledges message on Port: 62000

in this case port 62001 is for retrieving messages from the client to the server(me), also the server acknowledges messages on this port. and port 62000 is for sending messages from the server to the client, also the client acknowledges messages on this port.

My suggestion would be to just open 2 connections (2 Sockets, both accepting the same client(ip) but with 2 different ports), but seperate my own logic for acknowledging/sending and acknowledging/retrieving telegramms.

But since i havent found anyone having the same issue im just curious if TCP/IP is even meant to be used that way.

From what i've known, connections per TCP/IP normally means to set up one (or more) connections between server and client (server is listening - accepting the incoming client, and both communicate with one unique pair of ip adress and 1 given port). Ofcourse I described that in a very simple way, maybe too simple and even wrong. But the only exception i knew are FTP servers (one port for data, one for control)

As additional information, the communication is between PLC control and my Emulation tool (Im the Emulation(server) and the PLC is the Client) Furthermore i need to be able to send and retrieve on both ports (Clients) asynchronously. (maybe its crucial to mention that im using multiple threads, one for sending, one for retrieving, and one for processing)

Ive also posted the code im using right now for the standard procedure.(only for the ClientAccept method)

My question here is, would you(or anyone) use that code (it is used in some kind of framework, not developed by myself) or are there like 1000 better ways to establish tcp/ip connections in c# ?

I tried to just use the code i already have, and just adjusted it. So i was checking if there is already one Client connected, and if so, I would just accept a new Client. Its kinda hard to explain all of this, and get it to one question, (for me). Really sorry for that.

(I've researched for the last two days about TCP IP Connections, but there are only people asking about how to connect multiple clients all using the same port)

    private TcpClient _tcpclient;
    private NetworkStream _stream;

    //event when user manually resets the programm per reset button
    private readonly ManualResetEvent DarfVerbinden = new ManualResetEvent(false);


    public CConnectionTCP(string handlername, ITelegrammSpezifika telespe) : base(handlername, telespe)
    {

    }

    public TcpClient Client
    {
        get { return _tcpclient; }
    }

    public void ClientAccept()
    {
        //only connect if there is no connection already
        //only one thread can use this method at a given time
        lock (this)
        {
            //if the connection is available, allow connection
            _connectAvailable.WaitOne();
            TcpListener server = null;
            try
            {
                if (_tcpclient == null || _tcpclient.Client == null || !_tcpclient.Connected || !_tcpclient.Client.Connected)
                {
                    FireStatusChanged(StatusConnection.IsConnecting); 
                    server = new TcpListener(IPAddress.Any, _port);
                    server.Start();
                    while (Thread.CurrentThread.IsAlive && !server.Pending())
                    {
                        // if the user cancels the connection "status : disconnected" leave the method.
                        if (!_connectAvailable.WaitOne(0))
                        {
                            server.Stop();
                            return;
                        }
                        Thread.Sleep(100);
                    }
                    if (server.Pending())
                    {
                        //Accept the pending client connection and return a TcpClient object initialized for communication.
                        _tcpclient = server.AcceptTcpClient();
                        _stream = _tcpclient.GetStream();

                        FireStatusChanged(StatusConnection.Connected); // Connectionstatus is Connected
                    }
                }
            }
            catch (SocketException)
            {
                Logger.Log("Error", "Port is already in use", _handlername);
                Thread.Sleep(2000);
            }
            catch (Exception e)
            {
                Logger.Log("Error", "Error while connecting, Typ: " + e.GetType().ToString() + " Message: " + e.Message);
                Thread.Sleep(2000);
            }
            finally
            {
                if (server != null) server.Stop();
            }

        }
    }

One Connection (Sending and Retrieving) with 1 Connection partner but Sending and Retrieving are seperated channels (2 different Ports).

I dont really have any Idea how to realize this in a "good" way, because I must be able to have MULTIPLE Connections with MULTIPLE Clients at the SAME time BUT every Client is communicating with 2 different Ports, as described above.

Sorry my longest and first question ever here. I hope i did not break all the rules at once on this site.

Thank you already for your time!

  • 1
    Yes. TCP is meant to have one or more channels opened simultaneously. There are lots of standard protocols that use TCP with multiple port numbers. The TCP listener is means to accept many clients. The Listener has a main listening port and every time a new client connect a new socket is create an passed to the Asynchronous Accept Method. Since each client has two ports I would create a state object with two sockets.See the msdn Asynchronous Server example : https://docs.microsoft.com/en-us/dotnet/framework/network-programming/socket-code-examples. After reading example you can ask more. – jdweng Aug 19 '19 at 16:57
  • You certainly could make two separate connections. But there's absolutely no point in doing so. All you'd accomplish is to use more network resources to accomplish the same thing you can already do with a single connection. See marked duplicates for the _right_ way to do this. – Peter Duniho Aug 19 '19 at 18:24

0 Answers0