Check whether the port is called

Source: Internet
Author: User

The port is occupied and must be monitored. (This communication is simpler)

 

Code

 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");


}

}
}

Result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.