应工作需要,写段程序占用端口。
思想:通过Socket 建立一个连接,保持不间断。
这里是占用端口代码:
class UsePort
{
private int port; //设置端口
public int Port
{
get { return port; }
set { port = value; }
}
string ip;
public string Ip //IP 地址
{
get { return ip; }
set { ip = value; }
}
protected void SendMessage( string message) //建立一个SocketServer
{
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() //创建一个SocketClient
{
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(); //主线程调用Server,另起线程启动Client
up.SendMessage("pppppppppp");
}
}
以下代码监测 端口是否被占有: //实际就是在 cmd 里输入 “netstat -a” 察看是否有该端口信息
public static void CheckPort(string port){
Process p = new Process();
p.StartInfo = new ProcessStartInfo("netstat", "-a");
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string result = p.StandardOutput.ReadToEnd();
// if (result.IndexOf(Environment.MachineName.ToLower() + ":" + port) >= 0) //这个有时候不好用
if (result.Contains(":" + port)) //这个比较好用的哦
Console.WriteLine(port+"端口被占用");
else
{
Console.WriteLine(port+"端口没被占用");
}
}