⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 program.cs

📁 用TCPListener模拟socket编程的一问一答聊天 基于控制台
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TCPServer
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpListener tcpl = new TcpListener(10000);
                tcpl.Start();

                Console.WriteLine("连接中......");

                TcpClient client = tcpl.AcceptTcpClient();
                NetworkStream ns = client.GetStream();

                while (true)
                {
                    byte[] data = new byte[1024];
                    int recv = ns.Read(data, 0, data.Length);
                    string message = Encoding.ASCII.GetString(data,0,recv);

                    Console.WriteLine(message+"   from"+client.Client.RemoteEndPoint.ToString());

                    string reply = Console.ReadLine();
                    data = Encoding.ASCII.GetBytes(reply);
                    ns.Write(data, 0, data.Length);
                }

                ns.Close();
                client.Close();
                tcpl.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine("客户端已经断开!");
            }
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -