admin 管理员组文章数量: 1184232
应工作需要,写段程序占用端口。
思想:通过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+"端口没被占用");
}
}
版权声明:本文标题:深入解析Flash中心:高效策略确保SWF文件安全地运行于开放端口 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1771885480a3549671.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论