Wednesday, December 28, 2022

Client Server C#

 using System;

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new server socket
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to a local endpoint
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 13000);
            serverSocket.Bind(localEndPoint);

            // Start listening for incoming connections
            serverSocket.Listen(10);

            Console.WriteLine("Waiting for a connection...");

            // Accept incoming connections
            Socket clientSocket = serverSocket.Accept();

            Console.WriteLine("Connected!");

            // Receive data from the client
            byte[] buffer = new byte[1024];
            int bytesReceived = clientSocket.Receive(buffer);
            string data = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
            Console.WriteLine("Received: " + data);

            // Send a response back to the client
            string response = "Thank you for connecting!";
            byte[] responseBuffer = Encoding.ASCII.GetBytes(response);
            clientSocket.Send(responseBuffer);

            // Close the socket
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }
}


********************

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new client socket
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Connect to the server
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000);
            clientSocket.Connect(serverEndPoint);

            Console.WriteLine("Connected to server!");

            // Send a message to the server
            string message = "Hello from the client!";
            byte[] buffer = Encoding.ASCII.GetBytes(message);
            clientSocket.Send(buffer);

            // Receive a response from the server
            buffer = new byte[1024];
            int bytesReceived = clientSocket.Receive(buffer);
            string response = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
            Console.WriteLine("Received: " + response);

            // Close the socket
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }
}

No comments:

Post a Comment

Коментар: