实现两个socket server

 

server1

using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Comm2
{
    public class SocketServer
    {
        // 定义委托,用于事件处理  
        public delegate void ClientConnectedHandler(object sender, Socket clientSocket);

        // 定义OnAccept事件  
        public event ClientConnectedHandler? OnAccept;

        private Socket _serverSocket;
        private Thread? _listenThread;
        private bool _isListening;

        public SocketServer()
        {            
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _isListening = false;
        }

        // 启动服务并监听连接  
        public void Start(int port)
        {
            if (_isListening)
            {
                throw new InvalidOperationException("Server is already listening.");
            }

            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            _serverSocket.Listen(100);
            _isListening = true;

            _listenThread = new Thread(ListenForClients);
            _listenThread.IsBackground = true;
            _listenThread.Start();
        }

        // 停止服务  
        public void Stop()
        {
            if (!_isListening)
            {
                return;
            }

            _isListening = false;
            _serverSocket.Close();

            if (_listenThread != null && _listenThread.IsAlive)
            {
                _listenThread.Join();
            }
        }

        // 监听客户端连接的方法  
        private void ListenForClients()
        {
            while (_isListening)
            {
                try
                {
                    Socket clientSocket = _serverSocket.Accept();
                    OnAccept?.Invoke(this, clientSocket);
                }
                catch (ObjectDisposedException)
                {
                    // Socket已经关闭,退出监听循环  
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error accepting client: " + ex.Message);
                }
            }
        }
    }
}

  

 

server2

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Comm2
{
    public class SocketServer2
    {
        private Socket _serverSocket;
        private bool _isListening;

        public SocketServer2()
        {            
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _isListening = false;
        }

        // 启动服务并监听连接  
        public void Start(int port)
        {
            if (_isListening)
            {
                throw new InvalidOperationException("Server is already listening.");
            }

            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            _serverSocket.Listen(100);
            _isListening = true;

        }

        // 停止服务  
        public void Stop()
        {
            if (!_isListening)
            {
                return;
            }
            _isListening = false;
            _serverSocket.Close();
        }

        // 监听客户端连接的方法  
        public Socket? AcceptOnce()
        {
            if (_isListening)
            {
                try
                {
                    Socket clientSocket = _serverSocket.Accept();
                    return clientSocket;
                }
                catch (ObjectDisposedException ex)
                {
                    Console.WriteLine("Socket已经关闭,退出监听循环: " + ex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error accepting client: " + ex.Message);
                }
            }
            return null;
        }
    }
}

  

client

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

namespace Comm2
{
    public class SocketClient
    {
        // 定义委托,用于事件处理  
        public delegate void MessageReceivedHandler(object sender, string message);

        // 定义事件  
        public event MessageReceivedHandler? OnMsg;

        private Socket _socket;
        private Thread? _receiveThread;
        private bool _isConnected;

        public SocketClient()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _isConnected = false;
        }

        // 连接到服务器  
        public void Connect(string serverIP, int serverPort)
        {
            try
            {
                _socket.Connect(new IPEndPoint(IPAddress.Parse(serverIP), serverPort));
                _isConnected = true;

                // 开始接收线程  
                _receiveThread = new Thread(ReceiveData);
                _receiveThread.IsBackground = true;
                _receiveThread.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error connecting to server: " + ex.Message);
            }
        }

        // 发送数据到服务器  
        public void Send(string message)
        {
            if (!_isConnected)
            {
                Console.WriteLine("Not connected to the server.");
                return;
            }

            byte[] dataToSend = Encoding.ASCII.GetBytes(message);
            try
            {
                _socket.Send(dataToSend);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error sending data: " + ex.Message);
            }
        }

        // 接收数据的方法  
        private void ReceiveData()
        {
            byte[] buffer = new byte[1024];
            while (_isConnected)
            {
                try
                {
                    int received = _socket.Receive(buffer);
                    if (received > 0)
                    {
                        string receivedMessage = Encoding.ASCII.GetString(buffer, 0, received);
                        OnMsg?.Invoke(this, receivedMessage);
                    }
                }
                catch (Exception ex)
                {
                    // 如果连接断开,则退出循环  
                    _isConnected = false;
                    Console.WriteLine("Disconnected from server. " + ex.Message);
                    break;
                }
            }

            // 关闭Socket  
            _socket.Close();
        }

        // 断开与服务器的连接  
        public void Disconnect()
        {
            if (_isConnected)
            {
                _isConnected = false;
                _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();

                if (_receiveThread != null && _receiveThread.IsAlive)
                {
                    _receiveThread.Join();
                    _receiveThread = null;
                }
            }
        }
    }
}

 

使用 客户端

using Comm2;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args) {

        int port = 1080;
        SocketClient client = new SocketClient();
        // 订阅OnMsg事件  
        client.OnMsg += (object sender, string message)=>
        {
            Console.WriteLine("Received from server: " + message);
        };
        // 连接到服务器  
        client.Connect("127.0.0.1", port);
        Task task1 = Task.Run(() => {
            for (int i = 0; i < 10; i++)
            {
                // 发送数据  
                client.Send("Hello, Server! " + i.ToString());
                Thread.Sleep(1000);
            }
            // 断开连接  
            client.Disconnect();
        });



        SocketClient client2 = new SocketClient();
        // 订阅OnMsg事件  
        client2.OnMsg += (object sender, string message) =>
        {
            Console.WriteLine("2 Received from server: " + message);
        };
        // 连接到服务器  
        client2.Connect("127.0.0.1", port);
        Task task2 = Task.Run(() =>
        {
            for (int i = 0; i < 10; i++)
            {
                // 发送数据  
                client2.Send("2 Hello, Server! " + i.ToString());
                Thread.Sleep(1000);
            }
            // 断开连接  
            client2.Disconnect();
        });

        Task.WaitAll([task1, task2]);

        // 等待用户输入以退出  
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();



    }
}

 

使用 服务端

using Comm2;
using System.Net.Sockets;
using System.Reflection;
using System.Text;

class Program
{

    private static int ctrlPort = 1080, dataPort = 2080;
    static void Main(string[] args)
    {
        SocketServer2 ctrlServer = new SocketServer2();
        ctrlServer.Start(ctrlPort);
        Task.Run(async () =>
        {
            Socket? clientSocket;
            while ((clientSocket = ctrlServer.AcceptOnce())!=null)
            {
                while(true)
                {
                    byte[] buffer = new byte[1024];
                    int received = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
                    if (received == 0) break; // 客户端断开连接  
                    string receivedData = Encoding.ASCII.GetString(buffer, 0, received);
                    Console.WriteLine("Received from client: " + receivedData);
                    string response = "Hello, resp:" + receivedData;
                    byte[] dataToSend = Encoding.ASCII.GetBytes(response);
                    await clientSocket.SendAsync(dataToSend, SocketFlags.None);
                }
            }

        });
        Console.Read();
    }

    static void Main2(string[] args)
    {
        SocketServer ctrlServer = new SocketServer();
        ctrlServer.OnAccept += onCtrlMsg;
        ctrlServer.Start(ctrlPort);

        SocketServer dataServer = new SocketServer();
        dataServer.OnAccept += onDataMsg;
        dataServer.Start(dataPort);

        Console.WriteLine("Hello, World! Running at port:" + ctrlPort.ToString() + " " + dataPort.ToString());
        Console.Read();
    }

    public static void onCtrlMsg(Object sender, Socket clientSocket)
    {
        Task.Run(async () =>
        {
            try
            {
                Console.WriteLine("New client connected.");
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int received = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
                    if (received == 0) break; // 客户端断开连接  
                    string receivedData = Encoding.ASCII.GetString(buffer, 0, received);
                    Console.WriteLine("Received from client: " + receivedData);
                    string response = "Hello, resp:" + receivedData;
                    byte[] dataToSend = Encoding.ASCII.GetBytes(response);
                    await clientSocket.SendAsync(dataToSend, SocketFlags.None);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error handling client: " + ex.Message);
            }
            finally
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                Console.WriteLine("Client disconnected.");
            }
        });
    }

    public static void onDataMsg(Object sender, Socket clientSocket)
    {
        Task.Run(async () =>
        {
            try
            {
                Console.WriteLine("2 New client connected.");
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int received = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
                    if (received == 0) break; // 客户端断开连接  
                    string receivedData = Encoding.ASCII.GetString(buffer, 0, received);
                    Console.WriteLine("2 Received from client: " + receivedData);
                    string response = "2 Hello, resp:" + receivedData;
                    byte[] dataToSend = Encoding.ASCII.GetBytes(response);
                    await clientSocket.SendAsync(dataToSend, SocketFlags.None);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("2 Error handling client: " + ex.Message);
            }
            finally
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                Console.WriteLine("2 Client disconnected.");
            }
        });
    }

}

  

  

 

 microsoft/reverse-proxy: A toolkit for developing high-performance HTTP reverse proxy applications. (github.com)

 

 tmoonlight/NSmartProxy: NSmartProxy是一款开源的内网穿透工具。采用.NET CORE的全异步模式打造。(NSmartProxy is an open source reverse proxy tool that creates a secure tunnel from a public endpoint to a locally service.) (github.com)

 

ivandgetic/v2rayReverseProxy (github.com)

  

autodotua/FrpGUI: 一个使用Avalonia开发的FRP(内网穿透/反向代理)的Windows/Linux/MacOS桌面GUI程序;A desktop GUI program developed using Avalonia for FRP (intranet penetration/reverse proxy) on Windows/Linux/MacOS. (github.com)

 

posted @ 2024-03-26 10:03  zyip  阅读(9)  评论(0编辑  收藏  举报