C#/.NET Socket的使用

客户端

/// <summary>
/// 发起socket请求
/// </summary>
class Program
{
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("启动一个Socket客户端链接");

            int port = 2018;
            string host = "127.0.0.1";//服务器端ip地址

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(ipe);

            while (true)
            {
                Console.WriteLine("请输入发送到服务器的信息:");
                string sendStr = Console.ReadLine();
                if (sendStr == "exit")
                    break;

                byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
                clientSocket.Send(sendBytes);

                //receive message
                string recStr = "";
                byte[] recBytes = new byte[4096];
                int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
                recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
                Console.WriteLine($"服务器返回:{recStr}");
            }
            clientSocket.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.Read();
    }
}

服务端

public static void Proccess()
{
    int port = 2018;
    string host = "127.0.0.1";

    IPAddress ip = IPAddress.Parse(host);
    IPEndPoint ipe = new IPEndPoint(ip, port);

    Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    sSocket.Bind(ipe);
    sSocket.Listen(0);
    Console.WriteLine("监听已经打开,请等待");

    //收到消息  接受一个socket链接
    Socket serverSocket = sSocket.Accept();
    Console.WriteLine("连接已经建立。。。");
    while (true)
    {
        string recStr = "";
        byte[] recByte = new byte[4096];
        int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
        recStr += Encoding.ASCII.GetString(recByte, 0, bytes);
        Console.WriteLine("服务器端获得信息:{0}", recStr);

        if (recStr.Equals("stop"))
        {
            serverSocket.Close();//关闭该socket对象
            Console.WriteLine("关闭链接。。。。");
            break;
        }

        //回发消息
        Console.WriteLine("请输入回发消息。。。。");
        string sendStr = Console.ReadLine(); //"send to client :hello world";
        byte[] sendByte = Encoding.ASCII.GetBytes(sendStr);
        serverSocket.Send(sendByte, sendByte.Length, 0);

    }
    sSocket.Close();//关闭server监听
}
发布了169 篇原创文章 · 获赞 136 · 访问量 9214

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/103992595