服务端(接收数据)

定义常量,用于表示发送字节的最大数

 const int BufferSize = 8096;
 Console.WriteLine("Server is running...");

设置IP和端口并进行侦听

IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
TcpListener listener = new TcpListener(ip, 8500);
listener.Start();
Console.WriteLine("Start Listening...");

提供客户端链接并接收挂起的连接请求(中断的方法);

TcpClient remoterClient = listener.AcceptTcpClient();

打印连接的的信息

Console.WriteLine("Client Connected!{0}<-{1}", remoterClient.Client.LocalEndPoint, remoterClient.Client.RemoteEndPoint);

创建Stream流,提供用于网络访问的基础数据流

NetworkStream streamToClient = remoterClient.GetStream();

定义字节类型的数组(用于接收客户端发过来的数据)并读取字节数

byte[] buffer = new byte[BufferSize];
int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
Console.WriteLine("Reading data,{0}bytes...", bytesRead);

将读取到的数据编码称为字符串

string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);//请求字符串

打印接收到的数据

Console.WriteLine("Received:{0}", msg);

客户端(发送数据)

创建TCP客户端链接

Console.WriteLine("Client Running...");
TcpClient client;

使用Try...catch语句连接服务端

try
            {
                client = new TcpClient();
                client.Connect("localhost", 8500);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }

打印连接信息

Console.WriteLine("Server Connected!{0}->{1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

定义字符串用于发送数据

string msg = "Welcome to C# Program";

创建Strem数据流来传送数据

NetworkStream streamToServer = client.GetStream();

定义字节型数组,将字符串数据编码成字节

byte[] buffer = Encoding.Unicode.GetBytes(msg);

将编码后的数据写入Stream流并打印发送的数据

streamToServer.Write(buffer, 0, buffer.Length);
Console.WriteLine("Send:{0}", msg);