本文整理汇总了C#中System.Net.Sockets.UdpClient.EndReceive方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.EndReceive方法的具体用法?C# UdpClient.EndReceive怎么用?C# UdpClient.EndReceive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.UdpClient
的用法示例。
在下文中一共展示了UdpClient.EndReceive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: thread
private void thread()
{
UdpClient ucl = new UdpClient(6000);
IAsyncResult iar = ucl.BeginReceive(null, null);
while (!exit)
{
if (!iar.AsyncWaitHandle.WaitOne(1000))
continue;
IPEndPoint ep = new IPEndPoint(0, 0);
byte[] data = ucl.EndReceive(iar, ref ep);
iar = ucl.BeginReceive(null, 0);
using (MemoryStream ms = new MemoryStream(data))
{
BinaryReader br = new BinaryReader(ms);
while (ms.Position < ms.Length)
{
CanMessage m = CanMessage.DeserializeFrom(br);
if (MessageReceived != null)
MessageReceived(this, m);
}
}
}
ucl.Close();
}
示例2: CreateResponseObservable
private static IObservable<EmpegLocator> CreateResponseObservable(UdpClient client)
{
// Don't call BeginReceive until someone subscribes.
return Observable.Defer(
() =>
{
IPEndPoint ep = null;
var receive = Observable.FromAsyncPattern(
client.BeginReceive,
ar => client.EndReceive(ar, ref ep));
// Repeat will repeatedly subscribe; Defer will call receive() each time.
return Observable.Defer(receive)
.Where(bytes => bytes.Length != 1)
.Select(bytes => EmpegLocator.Create(ep, bytes))
.Repeat();
});
}
示例3: thread
private void thread()
{
using (UdpClient ucl = new UdpClient(6000))
{
IAsyncResult iar = ucl.BeginReceive(null, null);
while (!exit)
{
WaitHandle.WaitAny(new [] { evt, iar.AsyncWaitHandle });
if (exit)
break;
IPEndPoint ep = new IPEndPoint(0, 0);
byte[] data = ucl.EndReceive(iar, ref ep);
iar = ucl.BeginReceive(null, 0);
Boards.GetOrAdd(ep, e => new BoardInfo(e)).ParseMessage(data);
}
ucl.Close();
}
}
示例4: FindServer
/// <summary>
/// Attemps to discover the server within a local network
/// </summary>
public void FindServer(Action<IPEndPoint> onSuccess)
{
// Create a udp client
var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()));
// Construct the message the server is expecting
var bytes = Encoding.UTF8.GetBytes(broadcastDiscoverMessage);
// Send it - must be IPAddress.Broadcast, 7359
var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);
// Send it
client.BeginSend(bytes, bytes.Length, targetEndPoint, iac => {
//client.EndReceive
client.BeginReceive(iar =>
{
IPEndPoint remoteEndPoint= null;
var result = client.EndReceive(iar, ref remoteEndPoint);
if (remoteEndPoint.Port == targetEndPoint.Port)
{
// Convert bytes to text
var text = Encoding.UTF8.GetString(result);
// Expected response : MediaBrowserServer|192.168.1.1:1234
// If the response is what we're expecting, proceed
if (text.StartsWith("mediabrowserserver", StringComparison.OrdinalIgnoreCase))
{
text = text.Split('|')[1];
var vals = text.Split(':');
onSuccess(new IPEndPoint(IPAddress.Parse(vals[0]), int.Parse(vals[1])));
}
}
}, client);
}, client);
}
示例5: DoReceive
static void DoReceive(UdpClient udpClient, byte[] rgbSent, List<KnownNXT> result, SamanthaDiscovery discParam)
{
udpClient.BeginReceive((IAsyncResult ar) => {
//
// Program.Trace("IPConnection.DoReceive");
//
SamanthaDiscovery disc = ar.AsyncState as SamanthaDiscovery;
lock (disc)
{
if (!disc.fCanceled)
{
// Get the bytes for the incoming packet
IPEndPoint epSender = null;
byte[] rgbReceived = udpClient.EndReceive(ar, ref epSender);
// Post another request so we see all responses
DoReceive(udpClient, rgbSent, result, discParam);
// Note that we see our own initial transmission as well as responses from
// actual Samantha modules. We'd like to distinguish the former as being
// send to the broadcast address, but it doesn't appear that we can get that
// info here. So we just compare to the packet we sent.
if (rgbSent.IsEqualTo(rgbReceived))
{
// It's just us
Program.Trace("samantha: saw our packet");
}
else
{
// It's a Samantha. The address of the Samantha we get from udpClient. The
// payload, though isn't especially useful to us: it appears to be two text lines
// followed by a one-byte status code. The first line seems to be the Netbios name
// by which we could locate the module, and the second is a text form of the module's
// MAC address. Observed values for the status are 'A' for active, and 'O' for
// offline. So we'll just snarf the address away and go through the ProbeForNXT logic later
// like the other connection types.
//
// Update: we actually want to dig the name string out and parse it. May as well, just
// in case the ProbeForNXT doesn't find anything.
//
Program.Trace("samantha: saw {0}", epSender.Address.ToString());
string sReceived = (new System.Text.ASCIIEncoding()).GetString(rgbReceived);
string[] lines = sReceived.Lines(StringSplitOptions.RemoveEmptyEntries);
// First three chars are 'NXT' prepended to the actual NXT name. So a brick named 'Foo'
// will show up as 'NXTFoo'.
string sNXT = lines[0].SafeSubstring(3).Trim();
lock (result) // the delegate is called on a worker thread with (to us) unknown concurrency
{
KnownNXT.AddKnownNXT(result, new KnownNXT(KnownNXT.CONNECTIONTYPE.IP, epSender.Address.ToString(), sNXT));
}
}
}
}
}, discParam);
}
示例6: ScanGrainBrains
public static bool ScanGrainBrains()
{
bool ret = false;
var Client = new UdpClient();
var ServerEp = new IPEndPoint(IPAddress.Any, 8888);
var raw = new byte[1024];
NetworkDiscoveryRequest request = new NetworkDiscoveryRequest();
request.Name = "NETWORK-DISCOVERY-MSG";
var ms = new MemoryStream();
request.WriteTo(ms);
Client.EnableBroadcast = true;
Client.Send(ms.GetBuffer(), (int)ms.Length, new IPEndPoint(IPAddress.Broadcast, 8888));
var rawr = new byte[15000];
var AsyncResponseData = Client.BeginReceive(null, null);
int timeToWait = 1000;
AsyncResponseData.AsyncWaitHandle.WaitOne(timeToWait);
if (AsyncResponseData.IsCompleted)
{
try
{
byte[] receivedData = Client.EndReceive(AsyncResponseData, ref ServerEp);
//Receive(ref ServerEp);
var msr = new MemoryStream(receivedData);
NetworkDiscoveryReply reply = new NetworkDiscoveryReply();
reply.MergeDelimitedFrom(msr);
Console.Out.WriteLine("Grainbrain is found at {0}", ServerEp.Address);
ipAddr = ServerEp.Address;
ret = true;
// EndReceive worked and we have received data and remote endpoint
}
catch (Exception ex)
{
Console.WriteLine("Caught exception {0}", ex);
// EndReceive failed and we ended up here
}
}
else
{
// The operation wasn't completed before the timeout and we're off the hook
}
Client.Close();
if (ret)
updateStatus();
return ret;
}
示例7: GetDateAsync
public Task<DateTime> GetDateAsync()
{
index++;
if (hosts.Length <= index)
{
throw new InvalidOperationException(
"After trying out all the hosts, was unable to find anyone that could tell us what the time is");
}
var host = hosts[index];
return Task.Factory.FromAsync<IPAddress[]>((callback, state) => Dns.BeginGetHostAddresses(host, callback, state),
Dns.EndGetHostAddresses, host)
.ContinueWith(hostTask =>
{
if (hostTask.IsFaulted)
{
log.DebugException("Could not get time from: " + host, hostTask.Exception);
return GetDateAsync();
}
var endPoint = new IPEndPoint(hostTask.Result[0], 123);
var socket = new UdpClient();
socket.Connect(endPoint);
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
var sntpData = new byte[SntpDataLength];
sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)
return Task.Factory.FromAsync<int>(
(callback, state) => socket.BeginSend(sntpData, sntpData.Length, callback, state),
socket.EndSend, null)
.ContinueWith(sendTask =>
{
if (sendTask.IsFaulted)
{
try
{
socket.Close();
}
catch (Exception)
{
}
log.DebugException("Could not send time request to : " + host, sendTask.Exception);
return GetDateAsync();
}
return Task.Factory.FromAsync<byte[]>(socket.BeginReceive, (ar) => socket.EndReceive(ar, ref endPoint), null)
.ContinueWith(receiveTask =>
{
if (receiveTask.IsFaulted)
{
try
{
socket.Close();
}
catch (Exception)
{
}
log.DebugException("Could not get time response from: " + host, receiveTask.Exception);
return GetDateAsync();
}
var result = receiveTask.Result;
if (IsResponseValid(result) == false)
{
log.Debug("Did not get valid time information from " + host);
return GetDateAsync();
}
var transmitTimestamp = GetTransmitTimestamp(result);
return new CompletedTask<DateTime>(transmitTimestamp);
}).Unwrap();
}).Unwrap();
}).Unwrap();
}
示例8: UdpGetInfoByIPPort
public string[] UdpGetInfoByIPPort(string ipAddress, int ipPort, string cmdstr, int idelay, ref string state)
{
if (basefun.IsCorrenctIP(ipAddress) == false) return null;
if (idelay == 0) idelay = 100;
int timeout = idelay;
byte[] bytOutBuffer = getByteBy16s(cmdstr);
IPEndPoint RemoteIpEndPoint = SetIPEndPoint(ipAddress, ipPort);
byte[] bytReceiveBuffer;
using (UdpClient udpClient = new UdpClient())
{
udpClient.Send(bytOutBuffer, bytOutBuffer.Length, RemoteIpEndPoint);
IPEndPoint from = new IPEndPoint(IPAddress.Any, 0);
IAsyncResult result = udpClient.BeginReceive(null, this);
result.AsyncWaitHandle.WaitOne(timeout, false);
if (!result.IsCompleted)
{
//throw SharpTimeoutException.Create(ipAddress, timeout);
udpClient.Close();
return null;
}
bytReceiveBuffer = udpClient.EndReceive(result, ref from);
string udpInfo = get16sByByte(bytReceiveBuffer);
udpInfo = SpecialRestore(udpInfo, "dddb", "db");
udpInfo = SpecialRestore(udpInfo, "dcdb", "c0");
//ȡ����ֵ16��������,������
string[] infos = AnalysisEateryResults(udpInfo, ref state);
udpClient.Close();
return infos;
}
}
示例9: GetInfo
public string GetInfo(string devpms, string cmdpms, string datapms, string OutString, ref string state, ref string cmdstring)
{
devObj devobj = new devObj();
string cmdstr = CommandString(devpms, cmdpms, datapms, ref devobj);
if (basefun.IsCorrenctIP(devobj.IP) == false) return null;
if (devobj.Delay == 0) devobj.Delay = 2000;
byte[] bytOutBuffer;
if (devobj.IsAsc)
{
string strhead = cmdstr.Substring(0, 2);
string strend = cmdstr.Substring(cmdstr.Length - 2, 2);
cmdstr = cmdstr.Substring(2, cmdstr.Length - 2);
cmdstr = cmdstr.Substring(0, cmdstr.Length - 2);
bytOutBuffer = getAscByteBy16s(cmdstr, strhead, strend);
}
else
bytOutBuffer = getByteBy16s(cmdstr);
IPEndPoint RemoteIpEndPoint = SetIPEndPoint(devobj.IP, basefun.toIntval(devobj.Port), devobj.Mode);
byte[] bytReceiveBuffer;
using (UdpClient udpClient = new UdpClient())
{
udpClient.Send(bytOutBuffer, bytOutBuffer.Length, RemoteIpEndPoint);
IPEndPoint from = new IPEndPoint(IPAddress.Any, 0);
IAsyncResult result = udpClient.BeginReceive(null, this);
result.AsyncWaitHandle.WaitOne(devobj.Delay, false);
if (!result.IsCompleted)
{
udpClient.Close();
return null;
}
bytReceiveBuffer = udpClient.EndReceive(result, ref from);
string udpInfo = "";
if (devobj.IsAsc)
{
string info = "";
char[] cbuff = new char[bytReceiveBuffer.Length - 2];
for (int i = 1; i < bytReceiveBuffer.Length - 1; i++)
{
cbuff[i - 1] = (char)bytReceiveBuffer[i];
info += Convert.ToString(cbuff[i - 1]);
}
//ȥ��֡ͷ��֡β
udpInfo = info;
}
else
udpInfo = get16sByByte(bytReceiveBuffer, true);
//�ָ�ת���ַ�
if (devobj.Exchanges != "")
{
string[] strExs = devobj.Exchanges.Split('#');
for (int i = 0; i < strExs.Length; i++)
{
string[] _a = strExs[i].Split('/');
udpInfo = SpecialRestore(udpInfo, _a[1], _a[0]);
}
}
//ȡ����ֵ16��������,������
//udpInfo = "7E7AF08110091227000012200100000000DCDE0F909B137D0100FF00000000F4060D";
string infos = AnalysisEateryResults(udpInfo, OutString, devobj, true, ref state);
udpClient.Close();
return infos;
}
}
示例10: Lookup
/// <summary>
/// Looks up a record in DNS.
/// </summary>
/// <param name="name">The name to lookup</param>
/// <param name="type">The type of record requested</param>
/// <returns>The records returned by the DNS server, if any</returns>
public override ResourceRecord[] Lookup(string name, RecordType type)
{
ushort transactionId = _nextTransId++;
string normName = NormalizeDomainName(name);
using (UdpClient udpClient = new UdpClient(0))
{
IAsyncResult result = udpClient.BeginReceive(null, null);
PacketWriter writer = new PacketWriter(1800);
Message msg = new Message();
msg.TransactionId = transactionId;
msg.Flags = new MessageFlags(false, OpCode.Query, false, false, false, false, ResponseCode.Success);
msg.Questions.Add(new Question() { Name = normName, Type = type, Class = RecordClass.Internet });
msg.WriteTo(writer);
byte[] msgBytes = writer.GetBytes();
foreach (var server in _servers)
{
udpClient.Send(msgBytes, msgBytes.Length, server);
}
for (int i = 0; i < maxRetries; ++i)
{
DateTime now = DateTime.UtcNow;
while (result.AsyncWaitHandle.WaitOne(Math.Max(responseTimeout - (DateTime.UtcNow - now).Milliseconds, 0)))
{
try
{
IPEndPoint sourceEndPoint = null;
byte[] packetBytes = udpClient.EndReceive(result, ref sourceEndPoint);
PacketReader reader = new PacketReader(packetBytes);
Message response = Message.Read(reader);
if (response.TransactionId == transactionId)
{
return response.Answers.ToArray();
}
}
catch
{
// Do nothing - bad packet (probably...)
}
}
}
}
return null;
}
示例11: GetInfo
public string GetInfo(string devpms, string cmdpms, string datapms, string OutString, ref string state)
{
devObj devobj = new devObj();
string cmdstr = CommandString(devpms, cmdpms, datapms, ref devobj);
if (basefun.IsCorrenctIP(devobj.IP) == false) return null;
if (devobj.Delay == 0) devobj.Delay = 2000;
byte[] bytOutBuffer;
if (devobj.IsAsc)
{
string strhead = cmdstr.Substring(0, 2);
string strend = cmdstr.Substring(cmdstr.Length - 2, 2);
cmdstr = cmdstr.Substring(2, cmdstr.Length - 2);
cmdstr = cmdstr.Substring(0, cmdstr.Length - 2);
bytOutBuffer = getAscByteBy16s(cmdstr, strhead, strend);
}
else
bytOutBuffer = getByteBy16s(cmdstr);
//string strasc = "";
//for (int i = 0; i < bytOutBuffer.Length; i++)
//{
// strasc = bytOutBuffer[i].
//}
byte[] bytReceiveBuffer;
//----- UDP ------//
if (devobj.Mode == 0)
{
SerialCommi serialcom = new SerialCommi();
serialcom.SetProtocolParam("COM1", devobj.baudRate, devobj.Delay);
bytReceiveBuffer = serialcom.SendCommand(cmdstr,true);
}
else
{
IPEndPoint RemoteIpEndPoint = SetIPEndPoint(devobj.IP, basefun.toIntval(devobj.Port), devobj.Mode);
UdpClient udpClient = new UdpClient();
udpClient.Send(bytOutBuffer, bytOutBuffer.Length, RemoteIpEndPoint);
IPEndPoint from = new IPEndPoint(IPAddress.Any, 0);
IAsyncResult result = udpClient.BeginReceive(null, this);
result.AsyncWaitHandle.WaitOne(devobj.Delay, false);
if (!result.IsCompleted)
{
udpClient.Close();
return null;
}
bytReceiveBuffer = udpClient.EndReceive(result, ref from);
udpClient.Close();
}
//-----------------
string udpInfo = "";
if (devobj.IsAsc)
{
string info = "";
char[] cbuff = new char[bytReceiveBuffer.Length - 2];
for (int i = 1; i < bytReceiveBuffer.Length - 1; i++)
{
cbuff[i - 1] = (char)bytReceiveBuffer[i];
info += Convert.ToString(cbuff[i - 1]);
}
//去掉帧头和帧尾
udpInfo = info;
}
else
udpInfo = get16sByByte(bytReceiveBuffer, true);
//恢复转义字符
if (devobj.Exchanges != "")
{
string[] strExs = devobj.Exchanges.Split('#');
for (int i = 0; i < strExs.Length; i++)
{
string[] _a = strExs[i].Split('/');
udpInfo = SpecialRestore(udpInfo, _a[1], _a[0]);
}
}
//取返回值16进制数组,并解析
string infos = AnalysisEateryResults(udpInfo, OutString, devobj, true, ref state);
return infos;
}
示例12: Test
public void Test()
{
System.Net.Sockets.UdpClient cli = new System.Net.Sockets.UdpClient(11000);
cli.BeginReceive(new AsyncCallback(x => {
}), null);
cli.BeginReceive(new AsyncCallback(x =>
{
IPEndPoint ep = null;
var ret = cli.EndReceive(x, ref ep);
}), null);
}
示例13: Query
// Wiresharkの表示を参考にした
public static XmlDocument Query(IPEndPoint ip, int millisecs) {
using (UdpClient client = new UdpClient(ip.AddressFamily)) {
client.Connect(ip);
Random rand = new Random();
ushort seed = (ushort)rand.Next();
{
MemoryStream os = new MemoryStream();
BEW wr = new BEW(os);
wr.Write(seed);
wr.Write((ushort)0);//Flags: 0x0000 (Name query)
wr.Write((ushort)1);//Questions: 1
wr.Write((ushort)0);//Answer RRs: 0
wr.Write((ushort)0);//Authority RRs: 0
wr.Write((ushort)0);//Additional RRs: 0
wr.Write((byte)32);
wr.Write(Encoding.ASCII.GetBytes("CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
wr.Write((byte)0);
wr.Write((ushort)0x21);//Type: NBSTAT
wr.Write((ushort)0x01);//Class: IN
byte[] bin = os.ToArray();
if (client.Send(bin, bin.Length) != bin.Length) throw new EndOfStreamException();
}
{
XmlDocument xmlo = new XmlDocument();
XmlElement elroot = xmlo.CreateElement("wins");
xmlo.AppendChild(elroot);
XmlElement elres = xmlo.CreateElement("response");
elroot.AppendChild(elres);
byte[] bin;
{
IPEndPoint ipr = new IPEndPoint(0, 0);
IAsyncResult ar = client.BeginReceive(CbReceived, null);
if (false == ar.AsyncWaitHandle.WaitOne(millisecs, false)) {
client.Close();
}
bin = client.EndReceive(ar, ref ipr);
}
MemoryStream si = new MemoryStream(bin, false);
BER br = new BER(si);
ushort rseed = br.ReadUInt16();
if (rseed != seed) throw new InvalidDataException();
ushort fl = br.ReadUInt16();
if (0 == (fl & 0x8000) || 0 != (fl & 15)) throw new InvalidDataException();
{
int cnt = br.ReadUInt16();
for (int x = 0; x < cnt; ) {
throw new NotSupportedException();
}
}
int[] acnt = new int[3];
acnt[0] = br.ReadUInt16();
acnt[1] = br.ReadUInt16();
acnt[2] = br.ReadUInt16();
for (int t = 0; t < 3; t++) {
XmlElement elrrs = null;
if (t == 0) elrrs = xmlo.CreateElement("answer-rrs");
if (t == 1) elrrs = xmlo.CreateElement("authority-rrs");
if (t == 2) elrrs = xmlo.CreateElement("additional-rrs");
elres.AppendChild(elrrs);
for (int x = 0; x < acnt[t]; x++) {
XmlElement ela = xmlo.CreateElement("answer");
elrrs.AppendChild(ela);
byte cb = br.ReadByte();
byte[] name = br.ReadBytes(cb);
ela.SetAttribute("raw-name", Encoding.ASCII.GetString(name));
byte nodeType = br.ReadByte();
ela.SetAttribute("node-type", nodeType.ToString("x2"));
int atype = br.ReadUInt16();
if (atype != 0x21) throw new NotSupportedException();
int aclass = br.ReadUInt16();
if (aclass != 1) throw new NotSupportedException();
uint attl = br.ReadUInt32();
ela.SetAttribute("ttl", attl.ToString());
br.ReadUInt16();
byte aNamecnt = br.ReadByte();
for (int a = 0; a < aNamecnt; a++) {
String aname = Encoding.Default.GetString(br.ReadBytes(15));
byte anty = br.ReadByte();
int afl = br.ReadUInt16();
XmlElement elan = xmlo.CreateElement("name");
ela.AppendChild(elan);
elan.SetAttribute("name", aname);
//.........这里部分代码省略.........
示例14: GetPublicIPAddress
public static IPAddress GetPublicIPAddress(string stunServer)
{
try
{
logger.Debug("STUNClient attempting to determine public IP from " + stunServer + ".");
using (UdpClient udpClient = new UdpClient(stunServer, m_defaultSTUNPort))
{
STUNMessage initMessage = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
byte[] stunMessageBytes = initMessage.ToByteBuffer();
udpClient.Send(stunMessageBytes, stunMessageBytes.Length);
IPAddress publicIPAddress = null;
ManualResetEvent gotResponseMRE = new ManualResetEvent(false);
udpClient.BeginReceive((ar) =>
{
try
{
IPEndPoint stunResponseEndPoint = null;
byte[] stunResponseBuffer = udpClient.EndReceive(ar, ref stunResponseEndPoint);
if (stunResponseBuffer != null && stunResponseBuffer.Length > 0)
{
logger.Debug("STUNClient Response to initial STUN message received from " + stunResponseEndPoint + ".");
STUNMessage stunResponse = STUNMessage.ParseSTUNMessage(stunResponseBuffer, stunResponseBuffer.Length);
if (stunResponse.Attributes.Count > 0)
{
foreach (STUNAttribute stunAttribute in stunResponse.Attributes)
{
if (stunAttribute.AttributeType == STUNAttributeTypesEnum.MappedAddress)
{
publicIPAddress = ((STUNAddressAttribute)stunAttribute).Address;
logger.Debug("STUNClient Public IP=" + publicIPAddress.ToString() + ".");
}
}
}
}
gotResponseMRE.Set();
}
catch (Exception recvExcp)
{
logger.Warn("Exception STUNClient Receive. " + recvExcp.Message);
}
}, null);
if (gotResponseMRE.WaitOne(STUN_SERVER_RESPONSE_TIMEOUT * 1000))
{
return publicIPAddress;
}
else
{
logger.Warn("STUNClient server response timedout after " + STUN_SERVER_RESPONSE_TIMEOUT + "s.");
return null;
}
}
}
catch (Exception excp)
{
logger.Error("Exception STUNClient GetPublicIPAddress. " + excp.Message);
return null;
//throw;
}
}
示例15: UdpClient
void IProxy.LaunchProxy()
{
if (_alreadyCalledProxyMethod)
{
return;
}
_alreadyCalledProxyMethod = true;
try
{
UdpClient client = new UdpClient(_src);
Socket server = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
// ---
AsyncCallback clientCallback = null;
AsyncCallback serverCallback = null;
// TODO: Only done once ... even so, put his in assync! :D
server.Connect(_target);
serverCallback = delegate(IAsyncResult res)
{
SocketError err = default(SocketError);
int bytes = server.EndSend(res, out err);
// Check if all was sent ...
if (err == SocketError.Success)
{
Trace.WriteLine(string.Format("Sent {0} bytes to server.", bytes));
}
else
{
Trace.WriteLine(string.Format("Error {0} on sending", err));
}
};
clientCallback = delegate(IAsyncResult res)
{
// Reattach listener asap
client.BeginReceive(clientCallback, client);
byte[] datagram = client.EndReceive(res, ref _src);
Trace.WriteLine(string.Format("Received {0} bytes from client.", datagram.Length));
// Send to target
Trace.WriteLine(string.Format("About to send {0} bytes to server", datagram.Length));
server.BeginSend(
datagram, 0, datagram.Length,
SocketFlags.None, serverCallback, server);
// --
};
IAsyncResult result = client.BeginReceive(clientCallback, client);
}
catch (Exception e)
{
throw e;
// TODO: Better exception message ...
//Trace.WriteLine("Exception at UdpProxy: " + e.Message);
}
}