program.cs
来自「用TCPListener模拟socket编程的一问一答聊天 基于控制台」· CS 代码 · 共 46 行
CS
46 行
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 + =
减小字号Ctrl + -
显示快捷键?