本文整理汇总了C#中System.Net.Sockets.Socket.ReceiveFrom方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.ReceiveFrom方法的具体用法?C# Socket.ReceiveFrom怎么用?C# Socket.ReceiveFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.ReceiveFrom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Server
private static void Server()
{
list = new List<IPAddress>();
const ushort data_size = 0x400; // = 1024
byte[] data;
while (ServerRun)
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort);
try
{
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
data = new byte[data_size];
if (!ServerRun) break;
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));
data = new byte[data_size];
if (!ServerRun) break;
recv = sock.ReceiveFrom(data, ref ep);
stringData = System.Text.Encoding.ASCII.GetString(data, 0, recv);
if (!list.Contains(IPAddress.Parse(ep.ToString().Split(':')[0])))
list.Add(IPAddress.Parse(ep.ToString().Split(':')[0]));
sock.Close();
}
catch { }
}
}
示例2: Main
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9000);
s.Bind(iep);
EndPoint remote = (EndPoint)iep;
byte[] data = new byte[1024];
int k = s.ReceiveFrom(data, ref remote);
Console.WriteLine("Loi chao tu Client:{0}",Encoding.ASCII.GetString(data,0,k));
data = new byte[1024];
data = Encoding.ASCII.GetBytes("Chao Client ket noi");
s.SendTo(data, remote);
while (true)
{
data = new byte[1024];
string st;
k=s.ReceiveFrom(data, ref remote);
st = Encoding.ASCII.GetString(data, 0, k);
Console.WriteLine("Du lieu tu Client Gui la:{0}", st);
if (st.ToUpper().Equals("QUIT"))
break;
st = st.ToUpper();
data = new byte[1024];
data = Encoding.ASCII.GetBytes(st);
s.SendTo(data, remote);
}
s.Close();
}
示例3: StartBroadcastServer
//static string broadCast = string.Empty;
public static void StartBroadcastServer()
{
for (; Program.isProgramAlive ; )
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, BroadcastRecievePort);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive...");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sendBroadcastAnswer();
data = new byte[1024];
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",
stringData, ep.ToString());
sendBroadcastAnswer();
sock.Close();
}
}
示例4: Main
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9000);
string st = "Chao Server";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(st);
s.SendTo(data, iep);
EndPoint remote=(EndPoint)iep;
data = new byte[1024];
int k=s.ReceiveFrom(data,ref remote);
Console.WriteLine("Loi chao tu Server:{0}", Encoding.ASCII.GetString(data, 0, k));
while (true)
{
Console.Write("Nhap du lieu gui len Server:");
string st1 = Console.ReadLine();
byte[] dl = new byte[1024];
dl = Encoding.ASCII.GetBytes(st1);
s.SendTo(dl, remote);
if (st1.ToUpper().Equals("QUIT"))
break;
dl = new byte[1024];
int k1=s.ReceiveFrom(dl, ref remote);
Console.WriteLine("Du lieu tu Server la:{0}", Encoding.ASCII.GetString(dl, 0, k1));
}
s.Close();
}
示例5: Main
static void Main(string[] args)
{
byte[] data = new byte[1024];
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("38.98.173.2"), 58642);
//IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 58642);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true)
{
input = Console.ReadLine();
if (input == "exit")
break;
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping client");
server.Close();
}
示例6: Listen
public void Listen()
{
int port = 9050;
if (Options.listenMode != 0)
{
port = Options.listenMode;
}
int recv;
byte[] data = new byte[4096];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
newsock.Bind(ipep);
Console.WriteLine("Listening on UDP port " + port + " for squid log messages.");
//Console.WriteLine("Waiting for a client...");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
if (Options.debug == true)
{
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
var initSeparatedMessages = Encoding.ASCII.GetString(data, 0, recv).Split((new char[] { '\n', '\r' }), StringSplitOptions.RemoveEmptyEntries);
HelperMethods.addLog(initSeparatedMessages);
while (true)
{
data = new byte[4096];
recv = newsock.ReceiveFrom(data, ref Remote);
if (Options.debug == true)
{
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
}
var separatedMessages = Encoding.ASCII.GetString(data, 0, recv).Split((new char[] {'\n', '\r'}), StringSplitOptions.RemoveEmptyEntries);
HelperMethods.addLog(separatedMessages);
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
示例7: Start
public static void Start()
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
listener.Bind(new IPEndPoint(IPAddress.Any, PORT));
Console.WriteLine("Waiting for a connection..." + GetLocalIpAddress());
while (true) {
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
StateObject state = new StateObject();
state.WorkSocket = listener;
listener.ReceiveFrom(state.Buffer, ref remoteEndPoint);
var rawMessage = Encoding.UTF8.GetString(state.Buffer);
var messages = rawMessage.Split(';');
if (messages.Length > 1) {
var command = messages[0];
var deviceName = messages[1];
Console.WriteLine("Command is received from Device Name +"+deviceName+"+");
string[] portno = remoteEndPoint.ToString().Split(':');
Send(portno[1],remoteEndPoint);
}
}
}
示例8: Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
int address_len, port_len;
int offset = 0;
IPAddress ia = IPAddress.Any;
IPEndPoint ie = new IPEndPoint(ia, 8000);
EndPoint iep = (EndPoint)ie;
char[] send_data = new char[1024];
Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//test.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.BlockSource, false);
test.Bind(ie);
//test.Listen(5);
//Socket newSocket = test.Accept();
byte[] data = new byte[1024];
//newSocket.Receive(data);
test.ReceiveFrom(data, ref iep);
address_len = Convert.ToInt16(Encoding.ASCII.GetString(data).Substring(0,3));
port_len = Convert.ToInt16(Encoding.ASCII.GetString(data).Substring(4+address_len,4));
IPEndPoint ie2 = new IPEndPoint(IPAddress.Parse(Encoding.ASCII.GetString(data).Substring(4, address_len)), Convert.ToInt16(Encoding.ASCII.GetString(data).Substring(8 + address_len, port_len)));
//IPEndPoint ie2 = new IPEndPoint(IPAddress.Loopback, 8001);
EndPoint iep2 = (EndPoint)ie2;
richTextBox1.Text += Encoding.ASCII.GetString(data).Substring(8+address_len+port_len);
send_data = fillUDP.fillingUDP(out offset, Listen_port);
test.SendTo(Encoding.ASCII.GetBytes(send_data), iep2);
test.Close();
}
示例9: SendMsgWithReceive
public string SendMsgWithReceive(string ipaddress, int port, string sendData)
{
try
{
byte[] bytesSent;
byte[] buffer = new byte[1024];
bytesSent = Encoding.UTF8.GetBytes(sendData);
EndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port);
Socket clientSocket = new Socket(SocketType.Dgram, ProtocolType.Udp);
clientSocket.SendTo(bytesSent, bytesSent.Length, SocketFlags.None, ipe);
int receiveCount = clientSocket.ReceiveFrom(buffer, SocketFlags.None, ref ipe);
string data = Encoding.UTF8.GetString(buffer, 0, receiveCount);
clientSocket.Close();
clientSocket = null;
return data;
}
catch (Exception ex)
{
}
return null;
}
示例10: Main
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
Socket newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
serverin("files/serverin.txt");
//LISTEN TO ANY ip on port 950
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, PORT);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
//BIND ANY CONNECTION ON ENDPOINT TO NEWSOCKET
newsocket.Bind(endpoint);
Console.WriteLine("waiting for a client ...");
//WAIT FOR CLIENT TO Request data
recv = newsocket.ReceiveFrom(data, ref Remote);
//store end point in Remote
string filename = Encoding.ASCII.GetString(data);
filename = filename.Replace("\0", string.Empty);
Console.WriteLine("Received request for file: " + filename);
startChild(filename, Remote, newsocket);
Console.WriteLine("Sending Complete");
Console.ReadLine();
}
示例11: NTPTime
/// <summary>
/// Try to update both system and RTC time using the NTP protocol
/// </summary>
/// <param name="TimeServer">Time server to use, ex: pool.ntp.org</param>
/// <param name="GmtOffset">GMT offset in minutes, ex: -240</param>
/// <returns>Returns true if successful</returns>
public DateTime NTPTime(string TimeServer, int GmtOffset = 0)
{
Socket s = null;
DateTime resultTime = DateTime.Now;
try
{
EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] ntpData = new byte[48];
Array.Clear(ntpData, 0, 48);
ntpData[0] = 0x1B; // Set protocol version
s.SendTo(ntpData, rep); // Send Request
if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
{
s.ReceiveFrom(ntpData, ref rep); // Receive Time
byte offsetTransmitTime = 40;
ulong intpart = 0;
ulong fractpart = 0;
for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
s.Close();
resultTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
Utility.SetLocalTime(resultTime.AddMinutes(GmtOffset));
}
s.Close();
}
catch
{
try { s.Close(); }
catch { }
}
return resultTime;
}
示例12: getUdpLine
public static string getUdpLine(Socket sock, EndPoint ep)
{
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
return stringData;
}
示例13: Main
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
int port = 9999;
IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, port);
byte[] rec = new byte[256];
EndPoint ep = (EndPoint)iep;
s.ReceiveTimeout = 1000;
String msg;
Boolean on = true;
do
{
Console.Write(">");
msg = Console.ReadLine();
if (msg.Equals("Q"))
{
on = false;
}
else
{
s.SendTo(Encoding.ASCII.GetBytes(msg), ep);
while (!Console.KeyAvailable)
{
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
EndPoint Palvelinep = (EndPoint)remote;
int paljon = 0;
try
{
paljon = s.ReceiveFrom(rec, ref Palvelinep);
// splitataan string, onko pituus 2
String rec_string = Encoding.ASCII.GetString(rec, 0, paljon);
char[] delim = { ';' };
String[] palat = rec_string.Split(delim, 2);
if (palat.Length < 2)
{
// lähetä virheviesti
}
else
{
Console.WriteLine("[{0}:{1}]", palat[0], palat[1]);
}
}
catch
{
}
}
}
} while (on);
s.Close();
}
示例14: computerFinderListener_DoWork
private void computerFinderListener_DoWork(object sender, DoWorkEventArgs e)
{
Socket sockl = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipepl = new IPEndPoint(IPAddress.Any, 7829);
sockl.Bind(ipepl);
EndPoint ep = ipepl as EndPoint;
Byte[] recv = new Byte[1024];
sockl.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
while (!computerFinderListener.CancellationPending)
{
try
{
recv = new Byte[1024];
sockl.ReceiveFrom(recv, ref ep);
String[] recvl = Encoding.UTF8.GetString(recv).Substring(4).TrimEnd('\0').Split(',');
computerFinderListener.ReportProgress(-1, new CompFound()
{
hostname = recvl[0],
ip = recvl[1]
});
}
catch (Exception)
{
//do nothing, timeout is only thing that can throw an exception anyway
}
}
sockl.Close();
}
示例15: Read
/// <summary>
/// Reads an IcmpPacket from the wire using the specified socket from the specified end point
/// </summary>
/// <param name="socket">The socket to read</param>
/// <param name="packet">The packet read</param>
/// <param name="ep">The end point read from</param>
/// <returns></returns>
public virtual bool Read(Socket socket, EndPoint ep, int timeout, out IcmpPacket packet, out int bytesReceived)
{
const int MAX_PATH = 256;
packet = null;
bytesReceived = 0;
/*
* check the parameters
* */
if (socket == null)
throw new ArgumentNullException("socket");
if (socket == null)
throw new ArgumentNullException("ep");
// see if any data is readable on the socket
bool success = socket.Poll(timeout * 1000, SelectMode.SelectRead);
// if there is data waiting to be read
if (success)
{
// prepare to receive data
byte[] bytes = new byte[MAX_PATH];
bytesReceived = socket.ReceiveFrom(bytes, bytes.Length, SocketFlags.None, ref ep);
/*
* convert the bytes to an icmp packet
* */
// packet = IcmpPacket.FromBytes(bytes);
}
return success;
}