program.cs

来自「用TCPListener模拟socket编程的一问一答聊天 基于控制台」· CS 代码 · 共 39 行

CS
39
字号
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TCPClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpClient tcpc = new TcpClient("127.0.0.1", 10000);
                NetworkStream ns = tcpc.GetStream();


                while (true)
                {
                    string input = Console.ReadLine();
                    byte[] data = Encoding.ASCII.GetBytes(input);
                    ns.Write(data, 0, data.Length);

                    byte[] inbyte = new byte[1024];
                    int recv = ns.Read(inbyte, 0, inbyte.Length);
                    Console.WriteLine(Encoding.ASCII.GetString(inbyte, 0, recv) + "    from" + tcpc.Client.RemoteEndPoint.ToString());
                }
                ns.Close();
                tcpc.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("先开服务端!");
            }
        }
    }
}

⌨️ 快捷键说明

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