本文整理汇总了C#中Socket.ReceiveFrom方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.ReceiveFrom方法的具体用法?C# Socket.ReceiveFrom怎么用?C# Socket.ReceiveFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Socket
的用法示例。
在下文中一共展示了Socket.ReceiveFrom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BangChengMessageBYSocket
public string BangChengMessageBYSocket()
{
IPAddress serverIPAddress = IPAddress.Parse("127.0.0.1");//服务IP地址
int serverPort = 10001;//端口号
_client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_remoteEndPoint = new IPEndPoint(serverIPAddress, serverPort);
string Command = "Subscribe";//类型(订阅Subscribe/停止订阅UnSubscribe/发布Publish)
string message = Command + "," + "1001";
_client.SendTo(Encoding.ASCII.GetBytes(message), _remoteEndPoint);
_data = new byte[1024];
try
{
EndPoint publisherEndPoint = _client.LocalEndPoint;
_recv = _client.ReceiveFrom(_data, ref publisherEndPoint);
string msg = Encoding.ASCII.GetString(_data, 0, _recv) + "," + publisherEndPoint.ToString();
string value = msg.Split(",".ToCharArray())[1].ToString();
return string.Format("{0:F2}", value);
}
catch
{
return "0";
}
}
示例2: Socket_ReceiveFromDnsEndPoint_ArgumentException
public void Socket_ReceiveFromDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
int port = sock.BindToAnonymousPort(IPAddress.Loopback);
EndPoint endpoint = new DnsEndPoint("localhost", port);
Assert.Throws<ArgumentException>(() =>
{
sock.ReceiveFrom(new byte[10], ref endpoint);
});
}
}
示例3: Networking
public Networking()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.ReceiveTimeout = receiveTimeout;
recbuf = new byte[receiveBufferSize];
IPAddress ipaddr = IPAddress.Parse(serverAddress);
IPEndPoint ep = new IPEndPoint(ipaddr, serverPort);
server = (EndPoint)(new IPEndPoint(IPAddress.Any, clientPort));
socket.SendTo(Encoding.ASCII.GetBytes(SYN_MSG), ep);
socket.ReceiveFrom(recbuf, ref server);
Send(ACK_MSG);
}
示例4: AdvSndRcvData
private static int AdvSndRcvData(Socket s, byte[] message, EndPoint rmtdevice)
{
int recv = 0;
int retry = 0;
while (true)
{
Console.WriteLine("Attempt #{0}", retry);
try
{
s.SendTo(message, message.Length, SocketFlags.None, rmtdevice);
data = new byte[size];
recv = s.ReceiveFrom(data, ref Remote);
} catch (SocketException e)
{
if (e.ErrorCode == 10054)
recv = 0;
else if (e.ErrorCode == 10040)
{
Console.WriteLine("Error receiving packet");
size += 10;
recv = 0;
}
}
if (recv > 0)
{
return recv;
} else
{
retry++;
if (retry > 4)
{
return 0;
}
}
}
}
示例5: Main
public static void Main()
{
int receivedDataLength;
byte[] data = new byte[1024];
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9999);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
socket.Bind(ip);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
while(true)
{
data = new byte[1024];
receivedDataLength = socket.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
socket.SendTo(data, receivedDataLength, SocketFlags.None, Remote);
}
}
示例6: ReceiveData
// -------------------------------------------------------------------------
void ReceiveData()
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, multicastPort);
EndPoint wtf = (EndPoint) anyIP;
try {
Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse(multicastIP)));
udpSocket.Bind(anyIP);
while (Thread.CurrentThread.IsAlive)
{
if (udpSocket.Poll(1, SelectMode.SelectRead)) {
dataMutex.WaitOne();
byte[] buffer = new byte[1500];
int trueSize = udpSocket.ReceiveFrom(buffer, ref wtf);
byte[] trimmedBuffer = new byte[trueSize];
Array.Copy(buffer, trimmedBuffer, trueSize);
dataList.Add(trimmedBuffer);
dataMutex.ReleaseMutex();
}
Thread.Sleep(10);
}
} catch(Exception e) {
print(e.ToString());
}
}
示例7: Socket_ReceiveFromDnsEndPoint_Throws
public void Socket_ReceiveFromDnsEndPoint_Throws()
{
// "The parameter remoteEP must not be of type DnsEndPoint."
using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
{
int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback);
EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6);
Assert.Throws<ArgumentException>(() =>
{
int received = socket.ReceiveFrom(new byte[1], ref receivedFrom);
});
}
}
示例8: Socket_ReceiveFromV4IPEndPointFromV4Client_Throws
[Fact] // Base case
public void Socket_ReceiveFromV4IPEndPointFromV4Client_Throws()
{
// "The supplied EndPoint of AddressFamily InterNetwork is not valid for this Socket, use InterNetworkV6 instead."
Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
socket.DualMode = false;
EndPoint receivedFrom = new IPEndPoint(IPAddress.Loopback, UnusedPort);
Assert.Throws<ArgumentException>(() =>
{
int received = socket.ReceiveFrom(new byte[1], ref receivedFrom);
});
}
示例9: ListenerThread
/// <summary>
/// Thread Functions which does all the SNMP Agent job
/// </summary>
public void ListenerThread() {
mSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
mSock.ReceiveTimeout = 2000;
IPEndPoint vEndPoint = new IPEndPoint(IPAddress.Any, 16100);
mSock.Bind(vEndPoint);
Debug.Log ("Agent: thread started");
byte[] vBuff = new byte[4096];
int vLen = 0;
while (true) {
if (this.mSock.Available > 0) {
EndPoint vSender = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
vLen = mSock.ReceiveFrom(vBuff, ref vSender);
//Debug.Log ("Agent: Data received (bytes): " + vLen);
SnmpPacket vPacket = new SnmpV1Packet("" + "public");
vPacket.decode(vBuff, vLen);
//Debug.Log("Agent: PDU decoded: " + vPacket.Pdu.VbCount);
Oid vOid = null;
responsePacket = new SnmpV1Packet("" + "public");
responsePacket.Pdu.ErrorStatus = 0; // no error
if (vPacket.Pdu != null && vPacket.Pdu.VbList != null) {
foreach (Vb vVb in vPacket.Pdu.VbList) {
Debug.Log(vVb.ToString());
vOid = vVb.Oid;
if (vPacket.Pdu.Type == PduType.Set)
ProcessSetRequest(vOid,vVb);
if (vPacket.Pdu.Type == PduType.GetNext){
GetNext(vOid);
break;
}
ProcessGetRequest(vOid);
}
}
//Debug.Log(vOid.ToString());
responsePacket.Pdu.Type = PduType.Response;
responsePacket.Pdu.RequestId = vPacket.Pdu.RequestId;
byte[] vOutBuff = responsePacket.encode();
mSock.SendTo(vOutBuff, vSender);
callPrint = true;
}
Thread.Sleep(1000);
}
}
示例10: SendToRecvFrom_Datagram_UDP
private static void SendToRecvFrom_Datagram_UDP(IPAddress leftAddress, IPAddress rightAddress)
{
// TODO #5185: Harden against packet loss
const int DatagramSize = 256;
const int DatagramsToSend = 256;
const int AckTimeout = 1000;
const int TestTimeout = 30000;
var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
left.BindToAnonymousPort(leftAddress);
var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
right.BindToAnonymousPort(rightAddress);
var leftEndpoint = (IPEndPoint)left.LocalEndPoint;
var rightEndpoint = (IPEndPoint)right.LocalEndPoint;
var receiverAck = new ManualResetEventSlim();
var senderAck = new ManualResetEventSlim();
var receivedChecksums = new uint?[DatagramsToSend];
var leftThread = new Thread(() =>
{
using (left)
{
EndPoint remote = leftEndpoint.Create(leftEndpoint.Serialize());
var recvBuffer = new byte[DatagramSize];
for (int i = 0; i < DatagramsToSend; i++)
{
int received = left.ReceiveFrom(recvBuffer, SocketFlags.None, ref remote);
Assert.Equal(DatagramSize, received);
Assert.Equal(rightEndpoint, remote);
int datagramId = (int)recvBuffer[0];
Assert.Null(receivedChecksums[datagramId]);
receivedChecksums[datagramId] = Fletcher32.Checksum(recvBuffer, 0, received);
receiverAck.Set();
Assert.True(senderAck.Wait(AckTimeout));
senderAck.Reset();
}
}
});
leftThread.Start();
var sentChecksums = new uint[DatagramsToSend];
using (right)
{
var random = new Random();
var sendBuffer = new byte[DatagramSize];
for (int i = 0; i < DatagramsToSend; i++)
{
random.NextBytes(sendBuffer);
sendBuffer[0] = (byte)i;
int sent = right.SendTo(sendBuffer, SocketFlags.None, leftEndpoint);
Assert.True(receiverAck.Wait(AckTimeout));
receiverAck.Reset();
senderAck.Set();
Assert.Equal(DatagramSize, sent);
sentChecksums[i] = Fletcher32.Checksum(sendBuffer, 0, sent);
}
}
Assert.True(leftThread.Join(TestTimeout));
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]);
}
}
示例11: StartReceive
public void StartReceive()
{
try
{
//Create a UDP socket.
soUdp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
soUdp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
soUdp.ReceiveTimeout = 2000;
IPEndPoint localIpEndPoint = new IPEndPoint(IPAddress.Parse(udpAddress.HostIP), (int)udpAddress.Sp);
soUdp.Bind(localIpEndPoint);
byte[] received = new Byte[UDP_MAX_PACKET_SIZE];
byte[] msgBuffer = null;
Dictionary<int, byte[]> messageDict = new Dictionary<int, byte[]>(100);
while (isRunning)
{
EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
int size = 0;
try
{
if (soUdp!=null && soUdp.IsBound)
size = soUdp.ReceiveFrom(received, ref remoteEP);
}
catch (SocketException seInner)
{
if (seInner.ErrorCode == (int)SocketError.TimedOut)
Console.WriteLine("Socket timedout " + udpAddress);
else
throw seInner;
}
if (size > 0)
{
byte[] data = new byte[size];
Buffer.BlockCopy(received, 0, data, 0, size);
//Console.WriteLine("received from "+ servicePort+":" + received);
UDPMessage udpMsg = new UDPMessage(data);
if (!messageDict.ContainsKey(udpMsg.MessageID))
{ // init buffer
msgBuffer = new byte[udpMsg.MessageSize];
messageDict.Add(udpMsg.MessageID, msgBuffer);
}
else
{
messageDict.TryGetValue(udpMsg.MessageID, out msgBuffer);
}
Buffer.BlockCopy(udpMsg.Data, 0, msgBuffer, udpMsg.MessageOffset, udpMsg.Data.Length);
if (udpMsg.MessageOffset + udpMsg.Data.Length >= udpMsg.MessageSize - 1)
{
owner.receiveMsg(msgBuffer);
messageDict.Remove(udpMsg.MessageID);
msgBuffer = null;
}
//String dataReceived = System.Text.Encoding.ASCII.GetString(received);
//Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes(returningString.ToCharArray());
//soUdp.SendTo(returningByte, remoteEP);
}
}
}
catch (SocketException se)
{
Console.WriteLine("A Socket Exception has occurred!" + se.ToString());
}
}
示例12: EnumPorts
public List<MFDevice> EnumPorts(TransportType type)
{
/*
We need to create two socket for discovery Udp multicast
socket sends discovery message
socket2 receive messages
*/
if (type != TransportType.Udp) //sanity check
type = TransportType.Udp;
this.m_deviceList.Clear(); //start anew
try
{
foreach (IPAddress address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
int num = 0; // num of bytes return with receive socket
int index = 0; // denotes the beginning of each stream from MF modules
int iy = 0; // counts macaddress bytes
byte[] buffer = new byte[0x400]; //data buffer
byte[] macarr = new byte[0x06]; //mac address from data buffer
Socket socket = null; //tx socket on host
Socket socket2 = null;//rx socket on host
IPEndPoint localEP = new IPEndPoint(address, 0);
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, this.m_DiscoveryMulticastPort);
IPEndPoint point3 = new IPEndPoint(address, this.m_DiscoveryMulticastPort);
IPEndPoint point4 = new IPEndPoint(this.m_DiscoveryMulticastAddress, this.m_DiscoveryMulticastPort);
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket2.Bind(point3);
socket2.ReceiveTimeout = 0x3e8;
socket2.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(this.m_DiscoveryMulticastAddressRecv, address));
socket.Bind(localEP);
socket.MulticastLoopback = false;
socket.Ttl = 1;
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0x40);
socket.SendTo(Encoding.ASCII.GetBytes(this.m_DiscoveryMulticastToken), SocketFlags.None, point4);
while (0 < (num = socket2.ReceiveFrom(buffer, index, buffer.Length - index, SocketFlags.None, ref remoteEP)))
{
MFDevice mfDev = new MFDevice();
mfDev.setPointRemoteIP(((IPEndPoint)remoteEP).Address.ToString()); //add Remote IP
mfDev.setPointRemotePort(((IPEndPoint)remoteEP).Port); //add Remote Port
mfDev.setPointRemoteAdrFamily(((IPEndPoint)remoteEP).AddressFamily.ToString()); //add Remote Type
//get/add mac address
iy = 0;
while (iy < 6)
{
macarr[iy] = buffer[index + 8 + iy];
iy++;
}
mfDev.GetMacAddr(macarr); //add Remote Mac Address
m_deviceList.Add(mfDev); //add object to Factory
index += num; // new ofset- remote dev answer simultaniously to multicast
socket2.ReceiveTimeout = 200;//timeout of 200ms
}
socket2.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new MulticastOption(this.m_DiscoveryMulticastAddressRecv));
}
catch (SocketException)
{
}
finally
{
if (socket2 != null)
{
socket2.Close();
socket2 = null;
}
if (socket != null)
{
socket.Close();
socket = null;
}
}
}
}
}
catch (Exception)
{
}
return m_deviceList;
}
示例13: Main
public static void Main(String[] args)
{
// Initialize the multicast address group and multicast port.
// Both address and port are selected from the allowed sets as
// defined in the related RFC documents. These are the same
// as the values used by the sender.
mcastAddress = IPAddress.Parse("230.0.0.1");
mcastPort = 11000;
try
{
mcastSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
IPAddress localIP = IPAddress.Any;
EndPoint localEP = (EndPoint)new IPEndPoint(localIP, mcastPort);
mcastSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress,
1);
mcastSocket.Bind(localEP);
// Define a MulticastOption object specifying the multicast group
// address and the local IPAddress.
// The multicast group address is the same as the address used by the server.
mcastOption = new MulticastOption(mcastAddress, localIP);
// Become a member of the multicast IP address
mcastSocket.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.AddMembership,
mcastOption);
bool done = false;
byte[] bytes = new Byte[100];
IPEndPoint groupEP = new IPEndPoint(mcastAddress, mcastPort);
EndPoint remoteEP = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
while (!done)
{
Console.WriteLine("Waiting for multicast packets.......");
Console.WriteLine("Enter ^C to terminate.");
mcastSocket.ReceiveFrom(bytes, ref remoteEP);
Console.WriteLine("Received broadcast from {0} :\n {1}\n",
remoteEP.ToString(),
Encoding.ASCII.GetString(bytes, 0, bytes.Length));
Array.Clear(bytes, 0, 99);
}
mcastSocket.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
示例14: ReceiveFrom_Helper
private void ReceiveFrom_Helper(IPAddress listenOn, IPAddress connectTo)
{
using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp))
{
serverSocket.ReceiveTimeout = 500;
int port = serverSocket.BindToAnonymousPort(listenOn);
SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port);
EndPoint receivedFrom = new IPEndPoint(connectTo, port);
int received = serverSocket.ReceiveFrom(new byte[1], ref receivedFrom);
Assert.Equal(1, received);
Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint));
IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);
}
}
示例15: UDPListen
private static void UDPListen()
{
Logger.Log (LogLevel.UserInfo, "UDP Listening.");
int recv;
byte[] data= new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_PORT);
UDP_SOCK = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
UDP_SOCK.Bind(ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)(sender);
while(true)
{
try
{
recv=UDP_SOCK.ReceiveFrom(data, ref remote);
string rdata = Encoding.ASCII.GetString(data,0, recv);
string result = ParseAndExecuteCommand(rdata.Trim());
//Logger.Log(LogLevel.Debug, String.Format("Sending back {0}", result));
UDP_SOCK.SendTo(Encoding.ASCII.GetBytes(result), remote);
} catch (Exception e) {
string error = string.Format ("Could not read from UDP sock. {0}", e.ToString ());
Logger.Log(LogLevel.Warning, error);
}
}
}