占用了端口,还得监测。(这个通信更简单)
代码
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");
}
}
}
结果: