本文整理汇总了C#中System.Net.IPEndPoint.Equals方法的典型用法代码示例。如果您正苦于以下问题:C# IPEndPoint.Equals方法的具体用法?C# IPEndPoint.Equals怎么用?C# IPEndPoint.Equals使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.IPEndPoint
的用法示例。
在下文中一共展示了IPEndPoint.Equals方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetEP
public void SetEP(IPEndPoint ep)
{
if (ep.Equals(_listen.EP)) {
return;
}
else {
_listen.EP = ep;
_listen.Stop();
}
}
示例2: Ctor_LongInt
public void Ctor_LongInt ()
{
IPEndPoint ep = new IPEndPoint (0, 80);
Assert.AreEqual (new IPAddress (0), ep.Address, "Address");
Assert.AreEqual (AddressFamily.InterNetwork, ep.AddressFamily, "AddressFamily");
Assert.AreEqual (80, ep.Port, "Port");
Assert.Throws<ArgumentNullException> (delegate {
ep.Create (null);
}, "Create(null)");
// note: documented as ArgumentException
Assert.Throws<ArgumentOutOfRangeException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork, 1);
Assert.IsTrue (sa.Size < 8, "Size");
ep.Create (sa);
}, "Create(bad-size)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.InterNetworkV6);
Assert.IsTrue (sa.Size >= 8, "SizeV6");
ep.Create (sa);
}, "Create(InterNetworkV6)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.Unknown);
ep.Create (sa);
}, "Create(Unknown)");
Assert.Throws<ArgumentException> (delegate {
SocketAddress sa = new SocketAddress (AddressFamily.Unspecified);
ep.Create (sa);
}, "Create(Unspecified)");
EndPoint ep2 = ep.Create (new SocketAddress (AddressFamily.InterNetwork));
Assert.IsFalse (ep.Equals (null), "Equals(null)");
Assert.IsTrue (ep.Equals (ep), "Equals(self)");
Assert.IsFalse (ep.Equals (ep2), "Equals(Create)");
Assert.AreEqual ("InterNetwork:16:{0,80,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize ().ToString (), "Serialize");
Assert.AreEqual ("0.0.0.0:80", ep.ToString (), "ToString");
}
示例3: EqualsIgnoreScopeId_Test
public void EqualsIgnoreScopeId_Test(
string sip1, int port1,
string sip2, int port2,
bool equalsOriginal,
bool equalsIgnore
)
{
IPAddress ip1;
IPAddress.TryParse(sip1, out ip1);
var ipep1 = new IPEndPoint(ip1, port1);
IPAddress ip2;
IPAddress.TryParse(sip2, out ip2);
var ipep2 = new IPEndPoint(ip2, port2);
Assert.AreEqual(equalsOriginal, ipep1.Equals(ipep2), "Equals()");
Assert.AreEqual(equalsIgnore, ipep1.EqualsIgnoreScopeId(ipep2), "EqualsIgnoreScopeId()");
}
示例4: Start
// Methods ============================================================================
public override void Start(IPEndPoint ep)
{
// Verify IPEndPoints
IPEndPoint[] globalEPs = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
foreach (IPEndPoint globalEP in globalEPs) {
if (ep.Equals(globalEP))
throw new ApplicationException(ep.ToString() + " is in listening.");
}
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Bind(ep);
/// ** Report ListenerStarted event
if (ListenStarted != null)
ListenStarted(this, new ListenEventArgs(ep));
EndPoint epClient = new IPEndPoint(IPAddress.Any, 0);
isExitThread = false;
while (true) {
if (server.Poll(500000, SelectMode.SelectRead)) {
int bytesRead = server.ReceiveFrom(readbuffer, readbuffer.Length, SocketFlags.None, ref epClient);
/// ** Report ClientReadMsg event
if (ClientRecvPack != null)
ClientRecvPack(this, new ClientEventArgs(ep, epClient, readbuffer.Take(bytesRead).ToArray()));
} else if (isExitThread == true) {
isExitThread = false;
break;
}
}
server.Close();
/// ** Report ListenerStopped event
if (ListenStopped != null)
ListenStopped(this, new ListenEventArgs(ep));
});
thread.IsBackground = true;
thread.Start();
}
示例5: GetServers
public IEnumerable<IPEndPoint> GetServers(Region region, string filter = null)
{
using (var client = new UdpClient())
{
int serverCount;
var anyEndpoint = new IPEndPoint(IPAddress.Any, 0);
var lastEndpoint = anyEndpoint;
do
{
serverCount = 0;
var query = new List<byte> { 0x31, (byte)region };
query.AddRange(Encoding.ASCII.GetBytes(lastEndpoint.ToString()));
query.Add(0); // ip termination
if (!String.IsNullOrWhiteSpace(filter)) query.AddRange(Encoding.ASCII.GetBytes(filter));
query.Add(0); // filter termination
client.Send(query.ToArray(), query.Count, _endpoint);
var serverData = client.Receive(ref AnyIpEndPoint);
using (var br = new BinaryReader(new MemoryStream(serverData)))
{
if (br.ReadInt32() != -1 || br.ReadInt16() != 0x0A66) yield break;
while (br.BaseStream.Position < br.BaseStream.Length)
{
var ipBytes = br.ReadBytes(4);
var port = (ushort)IPAddress.NetworkToHostOrder(br.ReadInt16());
var server = new IPEndPoint(new IPAddress(ipBytes), port);
if (server.Equals(anyEndpoint)) yield break;
yield return server;
lastEndpoint = server;
serverCount++;
}
}
} while (serverCount > 0);
}
}
示例6: ConnectToPeerAsync
public async Task ConnectToPeerAsync(IPEndPoint remoteEndpoint)
{
if (remoteEndpoint.Equals(LocalEndpoint)) return;
RemoteNode remoteNode;
lock (unconnectedPeers)
{
unconnectedPeers.Remove(remoteEndpoint);
}
lock (pendingPeers)
{
lock (connectedPeers)
{
if (pendingPeers.Any(p => p.RemoteEndpoint == remoteEndpoint) || connectedPeers.ContainsKey(remoteEndpoint))
return;
}
remoteNode = new RemoteNode(this, remoteEndpoint);
pendingPeers.Add(remoteNode);
remoteNode.Disconnected += RemoteNode_Disconnected;
remoteNode.PeersReceived += RemoteNode_PeersReceived;
remoteNode.BlockReceived += RemoteNode_BlockReceived;
remoteNode.TransactionReceived += RemoteNode_TransactionReceived;
}
await remoteNode.ConnectAsync();
}
示例7: brainsplit
//throws InterruptedException
public void brainsplit(Message msg)
{
lock (this)
{
// current transaction can timeout
if (msg is CanCommitMessage)
{
// forbid new transactions
Logger.getInstance().log(
"Sending message to blocked cohort: " + msg.toString(),
LOGGING_NAME,
Logger.Level.INFO);
blockedCohort.putMessage(msg);
}
else if (msg is TransactionMessage)
{
// forbid new transactions
Logger.getInstance().log(
"Sending message to blocked coordinator: " + msg.toString(),
LOGGING_NAME,
Logger.Level.INFO);
blockedCoordinator.putMessage(msg);
}
else if (msg is RestoreIncentive)
{
// forbid new restoration
Logger.getInstance().log(
"Sending message to blocked restore coordinator: " + msg.toString(),
LOGGING_NAME,
Logger.Level.INFO);
blockedRestoreCoordinator.putMessage(msg);
}
else if (msg is HelloMessage)
{
HelloMessage hm = (HelloMessage)msg;
IPEndPoint node = new IPEndPoint(
hm.getSender().Address,
hm.ListeningPort
);
if (node.Equals(me))
return;
// try to add new node
TcpSender.getInstance().AddServerNode(node, queue);
}
else
{
Logger.getInstance().log(
"Undelivered message due to brainsplit: " + msg.toString(),
LOGGING_NAME,
Logger.Level.WARNING);
}
}
}
示例8: processHelloMessage
public void processHelloMessage(HelloMessage msg)
{
IPEndPoint node = new IPEndPoint(
msg.getSender().Address,
msg.ListeningPort
);
if (node.Equals(me))
return;
Logger.getInstance().log(
"Processing hello from - " + node.ToString() + " : " + msg.toString(),
LOGGING_NAME,
Logger.Level.INFO);
TcpSender.getInstance().AddServerNode(node, queue);
updateNodeSyncInfo(node, msg.Tables);
}
示例9: Start
public void Start(UInt16 port, IEnumerable<IHttpProcessor> processors)
{
Trace.TraceInformation("Starting");
lock (sync)
{
if (disposed) throw new ObjectDisposedException(Texts.ServerWasDisposed);
if (processors != null) this.processors = processors.ToArray();
var endPoint = new IPEndPoint(IPAddress.Any, port);
Trace.TraceInformation("\tEndpoint: {0}", endPoint);
if (Status == HttpServerStatus.Started)
{
var current = (IPEndPoint) socket.LocalEndPoint;
if (endPoint.Equals(current)) return;
throw AtlasException.ServerAlreadyRunning(current);
}
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(endPoint);
socket.Listen(0);
continueRunning = true;
threadLoop = new Thread(ProcessSocketConnections);
threadLoop.Start();
Status = HttpServerStatus.Started;
Trace.TraceInformation("\tStarted");
}
}
示例10: ReceiveVoiceAsync
private async Task ReceiveVoiceAsync(CancellationToken cancelToken)
{
var closeTask = cancelToken.Wait();
try
{
byte[] packet, decodingBuffer = null, nonce = null, result;
int packetLength, resultOffset, resultLength;
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
if ((_config.Mode & AudioMode.Incoming) != 0)
{
decodingBuffer = new byte[MaxOpusSize];
nonce = new byte[24];
}
while (!cancelToken.IsCancellationRequested)
{
await Task.Delay(1);
if (_udp.Available > 0)
{
#if !DOTNET5_4
packet = _udp.Receive(ref endpoint);
#else
//TODO: Is this really the only way to end a Receive call in DOTNET5_4?
var receiveTask = _udp.ReceiveAsync();
var task = Task.WhenAny(closeTask, receiveTask).Result;
if (task == closeTask)
break;
var udpPacket = receiveTask.Result;
packet = udpPacket.Buffer;
endpoint = udpPacket.RemoteEndPoint;
#endif
packetLength = packet.Length;
if (packetLength > 0 && endpoint.Equals(_endpoint))
{
if (State != ConnectionState.Connected)
{
if (packetLength != 70)
return;
string ip = Encoding.UTF8.GetString(packet, 4, 70 - 6).TrimEnd('\0');
int port = packet[68] | packet[69] << 8;
SendSelectProtocol(ip, port);
if ((_config.Mode & AudioMode.Incoming) == 0)
return; //We dont need this thread anymore
}
else
{
//Parse RTP Data
if (packetLength < 12) return;
if (packet[0] != 0x80) return; //Flags
if (packet[1] != 0x78) return; //Payload Type
ushort sequenceNumber = (ushort)((packet[2] << 8) |
packet[3] << 0);
uint timestamp = (uint)((packet[4] << 24) |
(packet[5] << 16) |
(packet[6] << 8) |
(packet[7] << 0));
uint ssrc = (uint)((packet[8] << 24) |
(packet[9] << 16) |
(packet[10] << 8) |
(packet[11] << 0));
//Decrypt
if (_isEncrypted)
{
if (packetLength < 28) //12 + 16 (RTP + Poly1305 MAC)
return;
Buffer.BlockCopy(packet, 0, nonce, 0, 12);
int ret = SecretBox.Decrypt(packet, 12, packetLength - 12, decodingBuffer, nonce, _secretKey);
if (ret != 0)
continue;
result = decodingBuffer;
resultOffset = 0;
resultLength = packetLength - 28;
}
else //Plain
{
result = packet;
resultOffset = 12;
resultLength = packetLength - 12;
}
/*if (_logLevel >= LogMessageSeverity.Debug)
RaiseOnLog(LogMessageSeverity.Debug, $"Received {buffer.Length - 12} bytes.");*/
ulong userId;
if (_ssrcMapping.TryGetValue(ssrc, out userId))
OnFrameReceived(userId, Channel.Id, result, resultOffset, resultLength);
}
}
}
}
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { } //Includes ObjectDisposedException
//.........这里部分代码省略.........
示例11: IsLocalAddress
static bool IsLocalAddress(IPEndPoint a_localAddr, IPEndPoint a_cmpAddr)
{
if (a_localAddr.Equals(a_cmpAddr))
return true;
if (a_localAddr.Port != a_cmpAddr.Port)
return false;
if (a_localAddr.Address.Equals(IPAddress.Any)) {
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress addr in host.AddressList) {
if (addr.AddressFamily == AddressFamily.InterNetwork) {
if (addr.Equals(a_cmpAddr.Address))
return true;
}
}
}
return false;
}
示例12: OnReceive
/*
* Commands are received asynchronously. OnReceive is the handler for them.
*/
private void OnReceive(IAsyncResult ar)
{
try
{
EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0);
//Get the IP from where we got a message.
clientSocket.EndReceiveFrom(ar, ref receivedFromEP);
//Convert the bytes received into an object of type Data.
Data msgReceived = new Data(byteData);
//Act according to the received message.
switch (msgReceived.cmdCommand)
{
//We have an incoming call.
case Command.Invite:
{
if (bIsCallActive == false)
{
//We have no active call.
//Ask the user to accept the call or not.
if (MessageBox.Show("Call coming from " + msgReceived.strName + ".\r\n\r\nAccept it?",
"VoiceChat", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
SendMessage(Command.OK, receivedFromEP);
vocoder = msgReceived.vocoder;
otherPartyEP = receivedFromEP;
otherPartyIP = (IPEndPoint)receivedFromEP;
InitializeCall();
}
else
{
//The call is declined. Send a busy response.
SendMessage(Command.Busy, receivedFromEP);
}
}
else
{
//We already have an existing call. Send a busy response.
SendMessage(Command.Busy, receivedFromEP);
}
break;
}
//OK is received in response to an Invite.
case Command.OK:
{
//Start a call.
InitializeCall();
break;
}
//Remote party is busy.
case Command.Busy:
{
MessageBox.Show("User busy.", "VoiceChat", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
}
case Command.Bye:
{
//Check if the Bye command has indeed come from the user/IP with which we have
//a call established. This is used to prevent other users from sending a Bye, which
//would otherwise end the call.
if (receivedFromEP.Equals (otherPartyEP) == true)
{
//End the call.
UninitializeCall();
}
break;
}
}
byteData = new byte[1024];
//Get ready to receive more commands.
clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref receivedFromEP, new AsyncCallback(OnReceive), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "VoiceChat-OnReceive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例13: GetOrCreateSource
/// <summary>
/// Gets or creates source. This method also does RFC 3550 8.2 "Collision Resolution and Loop Detection".
/// </summary>
/// <param name="rtcp_rtp">If true <b>src</b> is RTCP identifier, otherwise RTP identifier.</param>
/// <param name="src">Source SSRC or CSRC identifier.</param>
/// <param name="cname">RTCP SDES chunk CNAME. Must be passed only if <b>src</b> if from RTCP SDES chunk.</param>
/// <param name="packetEP">Packet sender end point.</param>
/// <returns>Returns specified source. Returns null if source has "collision or loop".</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>packetEP</b> is null reference.</exception>
private RTP_Source_Remote GetOrCreateSource(bool rtcp_rtp,uint src,string cname,IPEndPoint packetEP)
{
if(packetEP == null){
throw new ArgumentNullException("packetEP");
}
/* RFC 3550 8.2.
if(SSRC or CSRC identifier is not found in the source identifier table){
create a new entry storing the data or control source transport address, the SSRC or CSRC and other state;
}
else if(table entry was created on receipt of a control packet and this is the first data packet or vice versa){
store the source transport address from this packet;
}
else if(source transport address from the packet does not match the one saved in the table entry for this identifier){
// An identifier collision or a loop is indicated
if(source identifier is not the participant's own){
// OPTIONAL error counter step
if(source identifier is from an RTCP SDES chunk containing a CNAME item that differs from the CNAME in the table entry){
count a third-party collision;
}
else{
count a third-party loop;
}
abort processing of data packet or control element;
// MAY choose a different policy to keep new source
}
// A collision or loop of the participant's own packets
else if(source transport address is found in the list of conflicting data or control source transport addresses){
// OPTIONAL error counter step
if(source identifier is not from an RTCP SDES chunk containing a CNAME item or CNAME is the participant's own){
count occurrence of own traffic looped;
}
mark current time in conflicting address list entry;
abort processing of data packet or control element;
}
// New collision, change SSRC identifier
else{
log occurrence of a collision;
create a new entry in the conflicting data or control source transport address list and mark current time;
send an RTCP BYE packet with the old SSRC identifier;
choose a new SSRC identifier;
create a new entry in the source identifier table with the old SSRC plus the source transport address from
the data or control packet being processed;
}
}
*/
RTP_Source source = null;
lock(m_pMembers){
m_pMembers.TryGetValue(src,out source);
// SSRC or CSRC identifier is not found in the source identifier table.
if(source == null){
source = new RTP_Source_Remote(this,src);
if(rtcp_rtp){
source.SetRtcpEP(packetEP);
}
else{
source.SetRtpEP(packetEP);
}
m_pMembers.Add(src,source);
}
// Table entry was created on receipt of a control packet and this is the first data packet or vice versa.
else if((rtcp_rtp ? source.RtcpEP : source.RtpEP) == null){
if(rtcp_rtp){
source.SetRtcpEP(packetEP);
}
else{
source.SetRtpEP(packetEP);
}
}
// Source transport address from the packet does not match the one saved in the table entry for this identifier.
else if(!packetEP.Equals((rtcp_rtp ? source.RtcpEP : source.RtpEP))){
// Source identifier is not the participant's own.
if(!source.IsLocal){
if(cname != null && cname != source.CName){
m_RemoteCollisions++;
}
else{
m_RemotePacketsLooped++;
}
return null;
}
// A collision or loop of the participant's own packets.
else if(m_pConflictingEPs.ContainsKey(packetEP.ToString())){
if(cname == null || cname == source.CName){
m_LocalPacketsLooped++;
//.........这里部分代码省略.........
示例14: CreateAndSerialize
public void CreateAndSerialize()
{
SocketAddress addr = endPoint1.Serialize ();
EndPoint endPoint3 = endPoint2.Create (addr);
Assert.IsTrue (endPoint1.Equals (endPoint3), "#1");
IPAddress ipAddress = IPAddress.Parse ("255.255.255.255");
IPEndPoint endPoint4 = new IPEndPoint (ipAddress, MyMaxPort);
addr = endPoint4.Serialize ();
EndPoint endPoint5 = endPoint2.Create(addr);
Assert.IsTrue (endPoint4.Equals (endPoint5), "#2");
Assert.AreEqual (endPoint5.ToString (), "255.255.255.255:" + MyMaxPort, "#3");
}
示例15: FinishAccept
public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
{
ResetForNextRequest();
ReceiveBufferPos = 0;
_remoteEndPoint = remoteEndPoint;
_knownIsLocal = false;
_remoteIpAddress = null;
_remotePort = null;
if (!localEndPoint.Equals(_localEndPoint))
{
_localEndPoint = localEndPoint;
_localIpAddress = null;
_localPort = null;
}
_receiveBufferFullness = StartBufferOffset;
_receiving = true;
FinishReceive(buffer, offset, length);
}