Questo è il codice di esempio funzionante di un server TCP asincrono, il seguente server gestisce più client connessi contemporaneamente, ognuno sul proprio thread. Il seguente codice è relativamente breve e facile da riutilizzare.

Se non avete conoscenze di base su come funziona un server Tcp, è altamente raccomandato leggere prima: un altro mio post.

Codice

Il codice di tale sistema è semplice Decidiamo una porta e aprimo un server in ascolto su ogni IP address della macchina. (127.0.0.1, 192.168.x.x etc).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;      
using System.Net.Sockets;  

using System.Threading;

namespace ServerTest
{
    class Program
    {

        static void Main(string[] args)
        {
            Program main = new Program();
            main.server_start();  //starting the server

            Console.ReadLine();  
        }

        TcpListener server = new TcpListener(IPAddress.Any, 9999);   

        private void server_start()
        {
            server.Start();    
            accept_connection();  //accepts incoming connections
        }

        private void accept_connection()
        {
            //this is called asynchronously and will run in a different thread
            server.BeginAcceptTcpClient(handle_connection, server); 
        }

        //the parameter is a delegate, used to communicate between threads
        private void handle_connection(IAsyncResult result)  
        {
            accept_connection();  //once again, checking for any other incoming connections
            TcpClient client = server.EndAcceptTcpClient(result);  //creates the TcpClient

            NetworkStream ns = client.GetStream();

            /* here you can add the code to send/receive data */

        }

    }
}

Conclusione

Questo è fondamentalmente tutto il codice di cui avrete bisogno di sapere sui server tcp asincroni. Se ci sono domande, sentitevi liberi di lasciare un commento 🙂

Di Dalagh The Red

Programmatore Esperto, Nerd Veterano, Mago di Internet, essere umano; sì, in quest'ordine. Giocatore da tempi immemori di Magic ha scalato le classifiche per oltre un decennio, non dimenticando le sue sessioni GDR con diverse modalità. Lui Lui

Lascia un commento Annulla risposta