1. 发送程序
while (true)
{
string Value = GetXml.Getxmlvalue; //读取xml文件中的IP/PORT
//实例一个tcp客户端
TcpClient tcpClient = new TcpClient();
//连接xml文件中的ip与端口
tcpClient.Connect(Value.Split(':')[0], Int32.Parse(Value.Split(':')[1]));
//网络数据流,根据Tcp客户端发送
using (NetworkStream stream = tcpClient.GetStream())
{
//字节数组:将要发送的内容转换为字节数据
byte[] buffer = Encoding.UTF8.GetBytes("phone " + Value);
lock (stream)
{
//将字节数据一个一个的写入到数据流中
stream.Write(buffer, 0, buffer.Length);
Console.WriteLine("已发送");
}
}
//2s后再执行
Thread.Sleep(2000);
}
2.接收程序
Console.WriteLine("请输入本机ip:");
string ip = Console.ReadLine();
IPAddress address;
if(!IPAddress.TryParse(ip,out address))
{
Console.WriteLine("你输入的不是IP!");
Console.ReadLine();
}
IPAddress ipAddress = address;
Console.WriteLine("请输入端口:");
string port1 = Console.ReadLine();
int port = Int32.Parse(port1);
//实例Tcp监听器(根据输入的IP地址与端口)
TcpListener tcpListener = new TcpListener(ipAddress, port);
//监听程序启动
tcpListener.Start();
while (true)
{
//实例一个tcp客户端
TcpClient tcpClient = tcpListener.AcceptTcpClient();
//实例一个网络数据流
using (NetworkStream stream = tcpClient.GetStream())
{
//实例一个从字节流中读取字符
using (StreamReader sr = new StreamReader(stream))
{
string msg = sr.ReadToEnd();
Console.WriteLine("接收到的命令:" + msg);
}
}
}
3.效果图: