Multiple connections using a socket

Asked

Viewed 756 times

2

I have a connection socket that works well with TCP/UDP, the problem is that use Tcp1.Connect and it bars more than one connection. In an internet search I verified that the right one would use the Tcp1.BeginConnect which makes it possible to use more than one thread.

In my scenario I have foreach running along the lines of Grid catching the ip and equipment door. My doubt is how to mount several threads, or how to use the asynchronous connection within this loop.

Someone would have some example?

The code I’m using to send message to the equipment:

  TcpClient tcp1 = new TcpClient();
   UdpClient udp1 = new UdpClient();

    #region Menssagem Rápida
    private void cmd_msg_Click(object sender, EventArgs e)
    {
        string command = "";
        string preCommand = "";
        byte chkSum = 0;

        Random rnd = new Random();

        chaveAes[0] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[1] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[2] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[3] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[4] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[5] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[6] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[7] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[8] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[9] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[10] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[11] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[12] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[13] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[14] = Convert.ToByte(rnd.Next(1, 256));
        chaveAes[15] = Convert.ToByte(rnd.Next(1, 256));

        string comandoCatraca = "01+REON+00+20]5]" + mensagem_rapida + "]";
        command = "";
        command = command + (char)(2);

        preCommand = preCommand + (char)((comandoCatraca).ToString().Length);
        preCommand = preCommand + (char)(0);
        preCommand = preCommand + comandoCatraca;
        chkSum = calcCheckSumString(preCommand);

        command = command + preCommand;
        command = command + Convert.ToChar(chkSum);
        command = command + (char)(3);

        byte[] array = Encoding.ASCII.GetBytes(command);

        tcp1.Client.Send(array);
    }
    #endregion 

Does anyone know how I can get the data from the equipment in this method down past our friend Rick.

Thanks in advance.

  • 1

    Here you find a good example.

1 answer

1

Have this example, you can open several clients and test how the code works

Server:

class Program
  {
static ManualResetEvent allDone = new ManualResetEvent(false);

static void Main(string[] args)
{
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[0], 11000);
    Console.WriteLine("Local address and port : {0}", localEP.ToString());

    Socket listener = new Socket(localEP.Address.AddressFamily,
        SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEP);
        listener.Listen(10);

        while (true)
        {
            allDone.Reset();

            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(
                new AsyncCallback(AcceptCallback),
                listener);

            allDone.WaitOne();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("Closing the listener...");
}

static void AcceptCallback(IAsyncResult ar)
{
    // Get the socket that handles the client request.
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);

    // Signal the main thread to continue.
    allDone.Set();

    // Create the state object.
    StateObject state = new StateObject();
    state.WorkSocket = handler;
    handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0,
        new AsyncCallback(ReadCallback), state);
}

public static void ReadCallback(IAsyncResult ar)
{
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.WorkSocket;

    // Read data from the client socket.
    int read = handler.EndReceive(ar);

    // Data was read from the client socket.
    if (read > 0)
    {
        Console.WriteLine("[{0}] read {1} bytes", Thread.CurrentThread.ManagedThreadId, read);
        state.sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, read));
        handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReadCallback), state);
    }
    else
    {
        if (state.sb.Length > 1)
        {
            // All the data has been read from the client;
            // display it on the console.
            string content = state.sb.ToString();
            Console.WriteLine("[{0}] Read {1} bytes from socket.\n Data : {2}",
               Thread.CurrentThread.ManagedThreadId, content.Length, content);
        }
        handler.Close();
    }
}

public class StateObject
{
    public Socket WorkSocket = null;
    public const int BufferSize = 1024;
    public byte[] Buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

}

Client:

class Program
{
static void Main(string[] args)
{
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPEndPoint remoteEP = new IPEndPoint(ipHostInfo.AddressList[0], 11000);

    Socket s = new Socket(remoteEP.Address.AddressFamily,
        SocketType.Stream, ProtocolType.Tcp);
    s.Connect(remoteEP);

    Console.WriteLine("Connected, sending a few bytes...");
    byte[] bytes = Encoding.ASCII.GetBytes("hello");
    s.Send(bytes);

    Console.Write("Now press ENTER to send remaining bytes...");
    Console.ReadLine();
    bytes = Encoding.ASCII.GetBytes(" world");
    s.Send(bytes);

    s.Close();
    s.Dispose();
}}
  • 1

    I do not understand where you pass the ip for connection

  • You say on client or server?

  • Find the Ipendpoint & #Xa; line Example: string serverIP = "192.168.0.1"; string port = 8000; Ipendpoint remoteEP = new Ipendpoint(Ipaddress.Parse(serverIP), port);

  • 1

    On the same server, I need to use this part of the client as well ?

  • You need to put in both

  • Can pass the ip with the port, but gives an error in listener.Bind(localEP); says that the address is not valid in context, this part of the client for which server?

  • The ip that is in the client is the ip that it will connect, the server and the client needs is in the same port

  • very good example!

  • I have another question, I have other methods that use tcp1.Client.Send(array); to send massages to the equipment, how can I instantiate this example, to use in other part of my code?

  • Could you show me a piece of that code?

  • I can yes, I will edit my question and I will put there can be!?

  • I’d like to know how to instantiate tcp1.Send(bytes); for me to use elsewhere in the code. Put it as Global

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.