//-----------这是服务端 TcpListener------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
//IPEndPoint IPEPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),8888);
//TcpListener listener = new TcpListener(IPEPoint);
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
listener.Start();
Console.WriteLine("启动监听成功");
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
byte[] data = new byte[1024];
while (true)
{
if (stream.DataAvailable)
{
int length = stream.Read(data, 0, data.Length);
string receiveMsg = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("接收客户端发的数据: " + receiveMsg);
}
}
//stream.Close();
//listener.Stop();
//Console.ReadKey();
}
}
}
//--------- TcpClient 端 -----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("这是 TcpClient 端. ");
//声明一个客户端
TcpClient tcpClient = new TcpClient("127.0.0.1",8888);
//声明一个流用来写数据
NetworkStream stream = tcpClient.GetStream();
//从命令行接收输入
while (true)
{
Console.Write("请输入您要发送的数据: ");
string msg = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(msg);
stream.Write(data, 0, data.Length);
}
//stream.Close();
//tcpClient.Close();
//Console.ReadKey();
}
}
}