检验端口是否被调用
占用了端口,还得监测。(这个通信更简单)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ConsoleApplication1
{
class UsePort
{
private int port;
public int Port
{
get { return port; }
set { port = value; }
}
string ip;
public string Ip
{
get { return ip; }
set { ip = value; }
}
protected void SendMessage( string message)
{
TcpListener tListenser = null;
IPEndPoint ipPort = new IPEndPoint(IPAddress.Parse(ip),port);
try
{
tListenser = new TcpListener(ipPort);
tListenser.Start();
while (true)
{
Console.WriteLine("the port: " + Port.ToString() + " in " + Ip + " is used....");
Thread.Sleep(1000);
}
}
catch (Exception)
{
}
}
protected static void ReceiveMessage()
{
try
{
TcpClient client = new TcpClient("127.0.0.1", 5000);
Console.WriteLine("connection is OK");
}
catch(Exception)
{
Console.WriteLine("connection is Failed");
}
}
public static void Run()
{
UsePort up = new UsePort { Ip = "127.0.0.1", Port = 5000 };
new Thread(ReceiveMessage).Start();
up.SendMessage("pppppppppp");
}
}
}
结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步