pondelok, 30 január 2012 11:07 Written by 11162 times
Rate this item
(5 votes)

C# - TCP client server

Ukážeme si ako spraviť jednoduchú komunikáciu v TCP client-server. Pred kompiláciou zdrojového kódu treba zmeniť IP adresu v oboch programoch. V kóde je IP servera nastavená ako localhost 127.0.0.1 a port 8001. Po spustení servera začne server načúvať na nastavenom porte a čaká na pripojenie klienta. Po spustení klienta sa klient pripojí a odošle serveru našu správu.

Server po obdržaní správy ju zobrazí a pošle potvrdenie, ktoré dostane klient. Klient môže byť spustený na rovnakom počítači ako server alebo z iného počítača.

Kód v c# client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace TCP_client
{
    /// <summary>
    /// TCP client - www.projectik.eu
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string ipServer = "127.0.0.1";
                int portServer = 8001;
                String str = String.Empty;
                int timeout = 1000;
                int myTime = 0;
                bool statusTimeOut = false;
                List<byte> buffer = new List<byte>();
                Console.WriteLine("Connecting.....");
                //zadame text na odoslanie
                Console.WriteLine("Enter the string to be transmitted : ");
                //nacitanie zadaneho textu do premennej
                str = Console.ReadLine();
                using (TcpClient client = new TcpClient(ipServer, portServer))
                {
                    //Client sa uspesne pripojil
                    Console.WriteLine("Connected");
                    client.ReceiveTimeout = 3000;
                    client.SendTimeout = 3000;
                    using (NetworkStream stream = client.GetStream())
                    {
                        stream.Write(ASCIIEncoding.ASCII.GetBytes(str), 0, str.Length);
                        //cakanie na odpoved od servera
                        while (stream.DataAvailable == false)
                        {                           
                            Thread.Sleep(1);
                            if (++myTime > timeout)
                            {
                                statusTimeOut = true;
                                break;
                            }
                        }
                        if (statusTimeOut)
                        {
                             Console.Write("Time out.");
                            return;
                        }
                        //citaj pokial su data
                        while (stream.DataAvailable)
                        {
                            buffer.Add((byte)stream.ReadByte());
                        }
                    }
                    Console.WriteLine("Server reply : ");
                    //Vypiseme co poslal server
                    Console.WriteLine(ASCIIEncoding.ASCII.GetString(buffer.ToArray()));
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.Message);
            }
        }
    }
}

 

Kód v c# server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCPserver
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 8001;            
            IPAddress ipAddress = IPAddress.Any;        
            TcpClient client = null;
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] buffer;
            TcpListener listener = null;
            try
            {
                listener = new TcpListener(ipAddress, port);
                listener.Start();
                Console.WriteLine("Server is running");
                Console.WriteLine("Listening on port " + port);
                Console.WriteLine("Waiting for connections...");
                while (true)
                {
                    client = listener.AcceptTcpClient();
                    using (NetworkStream stream = client.GetStream())
                    {
                        buffer = new byte[1024];
                        stream.Read(buffer, 0, buffer.Length);
                        Console.WriteLine(encoder.GetString(buffer));
                        // server odpovie dakujem za spravicku
                        stream.Write(encoder.GetBytes("dakujem za spravicku"), 0, ("dakujem za spravicku").Length);                    
                    }
                }
            }
            catch (Exception ex1)
            {
                Console.WriteLine(ex1.Message);
            }
            finally
            {
                if (client != null)
                {
                    client.Close();
                }
                listener.Stop();
            }
        }
    }
}

 V nasledujúcom príklade vypustíme obe triedy TcpListener a TcpClient a namiesto toho priamo použijeme System.Net.Sockets.Socket triedy.

Kód v c# client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace TCP_client
{
    /// <summary>
    /// TCP client - www.projectik.eu
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                String str = String.Empty;
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);
                byte[] buffer = new byte[4096]; //buffer 4kB
                Console.WriteLine("Connecting.....");
                //zadame text na odoslanie
                Console.WriteLine("Enter the string to be transmitted : ");
                //nacitanie zadaneho textu do premennej
                str = Console.ReadLine();
                using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    sock.Connect(iep);
                    //Client sa uspesne pripojil
                    Console.WriteLine("Connected");
                    //set timeout
                    sock.ReceiveTimeout = 3000;
                    sock.SendTimeout = 3000;
                    //Convertovenie stringu na byte array
                    byte[] data = Encoding.ASCII.GetBytes(str);
                    //odoslanie spravy
                    sock.Send(data, data.Length, SocketFlags.None);
                    //prijatie odpovede od servera
                    int numberOfBytes = sock.Receive(buffer);
                    byte[] formatedBytes = new byte[numberOfBytes];
                    Array.Copy(buffer, formatedBytes, numberOfBytes);
                    //Vypiseme co poslal server
                    Console.WriteLine("Server reply : ");
                    Console.WriteLine(ASCIIEncoding.ASCII.GetString(formatedBytes.ToArray()));
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.Message);
            }
        }
    }
}

Kód v c# server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCPserver
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] buffer = new byte[4096];//4kb buffer
            try
            {
                Console.WriteLine("Server is running");
                Console.WriteLine("Waiting for connections...");
                using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    //nacuvanie od vsetkych IP adries
                    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8001);

                    sock.Bind(iep);
                    sock.Listen(1);
                    while (true)
                    {
                        Socket listener = sock.Accept();
                        // sock.Poll(0, SelectMode.SelectRead);                        
                        if (listener.Connected)
                        {
                            //prijatie odpovede od servera
                            int numberOfBytes = listener.Receive(buffer);
                            byte[] formatedBytes = new byte[numberOfBytes];
                            Array.Copy(buffer, formatedBytes, numberOfBytes);
                            //Vypiseme co poslal server
                            Console.WriteLine("Client send : ");
                            Console.WriteLine(ASCIIEncoding.ASCII.GetString(formatedBytes));
                        
                            //Odpoved servera
                            byte[] data = Encoding.ASCII.GetBytes("dakujem za spravicku");
                            listener.Send(data, data.Length, SocketFlags.None);
                        }
                    }
                }
            }
            catch (Exception ex1)
            {
                Console.WriteLine(ex1.Message);
            }        
        }
    }
}
Last modified on pondelok, 19 december 2016 21:27
Ing.Jaroslav Vadel

Som zakladateľom www.projectik.eu.

Hrám sa na programátora, ktorý ovláda:

c#,cpp,java,unity3d,php,html,NI testand,NI Vision Builder,Cognex In-Sight,NI LabView

"Naprogramovať program, ktorý funguje vie každy. Ale to, že program funguje ešte neznamena, že je napísany správne "

Website: www.projectik.eu

Related items