//-----------这是服务端 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];
//int length = stream.Read(data, 0, data.Length);
//string receiveMsg = Encoding.UTF8.GetString(data, 0, length);
BinaryReader br = new BinaryReader(stream);
string receiveMsg = br.ReadString();
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();
//从命令行接收输入
Console.Write("请输入您要发送的数据: ");
string msg = Console.ReadLine();
/*
//向服务端发送数据
//byte[] data = Encoding.UTF8.GetBytes(msg);
//把字节数组写到流上
//stream.Write(data, 0, data.Length);
*/
//以二进制方式操作流
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(msg);
stream.Close();
tcpClient.Close();
Console.ReadKey();
}
}
}