本文整理汇总了C#中System.Net.Sockets.Socket.BeginSendTo方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.BeginSendTo方法的具体用法?C# Socket.BeginSendTo怎么用?C# Socket.BeginSendTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.Socket
的用法示例。
在下文中一共展示了Socket.BeginSendTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FirstMessage
internal void FirstMessage(Socket udp,EndPoint sep)
{
DataHandle Handle = new DataHandle();
string _mess = Generate._AppID + "," + Generate._licenceKey + "," + Generate.GetMacAddress() + "," + udp.LocalEndPoint.ToString();
byte[] data = Handle.HaSe(1000,_mess);
udp.BeginSendTo(data, 0, data.Length, SocketFlags.None, sep, new AsyncCallback((async) => { }), udp);
}
示例2: btnOK_Click
private void btnOK_Click(object sender, EventArgs e)
{
strName = txtName.Text;
try
{
//Using UDP sockets
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
//IP address of the server machine
IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
//Server is listening on port 1000
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);
epServer = (EndPoint)ipEndPoint;
Data msgToSend = new Data ();
msgToSend.cmdCommand = Command.Login;
msgToSend.strMessage = null;
msgToSend.strName = strName;
byte[] byteData = msgToSend.ToByte();
//Login to the server
clientSocket.BeginSendTo(byteData, 0, byteData.Length,
SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例3: btnConnect_Click
//metodo eseguito al click sul pulsante connetti
private void btnConnect_Click(object sender, EventArgs e)
{
//vengono memorizzati il nome utente e
//viene aggiornata la casella di testo
_userName = txtUserName.Text.Trim();
_setText = SetText;
//viene creato e riempito un pacchetto di richiesta di join alla chat
Packet sendData = new Packet();
sendData.DataIdentifier = DataTypeIdentifier.Login;
sendData.UserName = _userName;
//viene creato un Socket UDP
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//viene creato un oggetto contenente l'indirizzo IP e la porta del server
IPAddress serverIP = IPAddress.Parse(txtServerAddress.Text);
int serverPort = int.Parse(txtServerPort.Text);
_epServer = new IPEndPoint(serverIP, serverPort);
//il pacchetto creato viene convertito in un'array di byte
_dataStream = sendData.ToByteArray();
//il pacchetto creato viene spedito al server
_clientSocket.BeginSendTo(_dataStream, 0, _dataStream.Length, SocketFlags.None, _epServer, SendData, null);
//tutti gli oggetti vengono sempre passati per referenza
//il client si mette ora in ascolto dei messaggi provenienti dal server
EndPoint ep = _epServer;
_dataStream = new byte[Properties.Settings.Default.MAX_PACKET_LENGTH];
_clientSocket.BeginReceiveFrom(_dataStream, 0, _dataStream.Length, SocketFlags.None, ref ep, ReceiveData, null);
}
示例4: DiscoverAsync
public static async Task<bool> DiscoverAsync(object state = null)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 1900);
byte[] outBuf = Encoding.ASCII.GetBytes(BroadcastPacket);
byte[] inBuf = new byte[4096];
int tries = MaxTries;
while (--tries > 0)
{
try
{
TaskFactory factory = new TaskFactory();
sock.ReceiveTimeout = DiscoverTimeout;
await factory.FromAsync(sock.BeginSendTo(outBuf, 0, outBuf.Length, 0, endpoint, null, null), end =>
{
sock.EndSendTo(end);
}).ConfigureAwait(false);
var ar = sock.BeginReceive(inBuf, 0, inBuf.Length, 0, null, null);
if (ar == null) throw new Exception("ar is null");
int length = await factory.FromAsync(ar, end => sock.EndReceive(end)).ConfigureAwait(false);
string data = Encoding.ASCII.GetString(inBuf, 0, length).ToLowerInvariant();
var match = ResponseLocation.Match(data);
if (match.Success && match.Groups["location"].Success)
{
System.Diagnostics.Debug.WriteLine("Found UPnP device at " + match.Groups["location"]);
string controlUrl = GetServiceUrl(match.Groups["location"].Value);
if (!string.IsNullOrEmpty(controlUrl))
{
_controlUrl = controlUrl;
System.Diagnostics.Debug.WriteLine("Found control URL at " + _controlUrl);
return true;
}
}
}
catch (Exception ex)
{
// ignore timeout exceptions
if (!(ex is SocketException && ((SocketException) ex).ErrorCode == 10060))
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
return false;
}
示例5: Send
void Send()
{
while (Environment.TickCount < _iTime)
{
IPEndPoint ipEndPoint = new IPEndPoint(Utils.ResolveHost(this._strHost), this._iPort);
Socket s = new Socket(AddressFamily.InterNetwork, this._strType == "Udp" ? SocketType.Dgram : SocketType.Stream, this._strType == "Udp" ? ProtocolType.Udp : ProtocolType.Tcp);
int iPort = _iPort == 0 ? Utils.RandomInt(1, 65500) : _iPort;
byte[] arr_bPacket = null;
switch (this._strType)
{
case "Udpflood":
arr_bPacket = Utils.GetBytes(Utils.RandomString(Utils.RandomInt(128, 512)));
s.BeginSendTo(arr_bPacket, 0, arr_bPacket.Length, SocketFlags.None, (EndPoint)ipEndPoint, new AsyncCallback(SendToCallback), s);
break;
case "Httpflood":
arr_bPacket = Utils.GetBytes(this.BuildPacket(false, -1));
s.Connect((EndPoint)ipEndPoint);
s.Send(arr_bPacket);
s.Close();
break;
case "Condis":
s.BeginConnect((EndPoint)ipEndPoint, new AsyncCallback(ConnectCallback), s);
break;
case "Slowpost":
int iPacketSize = Utils.RandomInt(128,512);
int iSent = 0;
arr_bPacket = Utils.GetBytes(this.BuildPacket(true, iPacketSize));
s.Connect((EndPoint)ipEndPoint);
s.Send(arr_bPacket);
while (iSent < iPacketSize)
{
iSent += s.Send(Utils.GetBytes(Utils.RandomString(1)));
Thread.Sleep(100);
}
s.Send(Utils.GetBytes("Connection: close"));
s.Close();
break;
default: break;
}
GC.Collect();
Thread.Sleep(10);
}
}
示例6: Arping
public void Arping( IPAddress ipToSearchFor )
{
string ownMAC;
string ownIP;
getLocalMacAndIP( out ownIP, out ownMAC );
char[] aDelimiter = { '.' };
string[] aIPReso = ipToSearchFor.ToString().Split( aDelimiter, 4 );
string[] aIPAddr = ownIP.Split( aDelimiter, 4 );
byte[] oPacket = new byte[] { /*0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
Convert.ToByte("0x" + ownMAC.Substring(0,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(2,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(4,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(6,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(8,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(10,2), 16),
0x08, 0x06,*/ 0x00, 0x01,
0x08, 0x00, 0x06, 0x04, 0x00, 0x01,
Convert.ToByte("0x" + ownMAC.Substring(0,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(2,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(4,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(6,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(8,2), 16),
Convert.ToByte("0x" + ownMAC.Substring(10,2), 16),
Convert.ToByte(aIPAddr[0], 10),
Convert.ToByte(aIPAddr[1], 10),
Convert.ToByte(aIPAddr[2], 10),
Convert.ToByte(aIPAddr[3], 10),
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
Convert.ToByte(aIPReso[0], 10),
Convert.ToByte(aIPReso[1], 10),
Convert.ToByte(aIPReso[2], 10),
Convert.ToByte(aIPReso[3], 10)};
Socket arpSocket;
arpSocket = new Socket( System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Raw );
//arpSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true );
arpSocket.EnableBroadcast = true;
EndPoint localEndPoint = new IPEndPoint( IPAddress.Any, 0 );
EndPoint remoteEndPoint = new IPEndPoint( ipToSearchFor, 0 );
arpSocket.Bind( localEndPoint );
arpSocket.BeginSendTo( oPacket,0,oPacket.Length,SocketFlags.None, remoteEndPoint, null, this);
byte[] buffer = new byte[100];
arpSocket.BeginReceiveMessageFrom( buffer, 0, 100, SocketFlags.None, ref remoteEndPoint, null, this);
}
示例7: btnConnect_Click
void btnConnect_Click(object sender, RoutedEventArgs e)
{
try
{
string msgConn = tbName.Text + " connected";
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress serverIP = IPAddress.Parse(tbIp.Text);
server = new IPEndPoint(serverIP, 30000);
epServer = (EndPoint)server;
byteData = Encoding.UTF8.GetBytes(msgConn);
clientSocket.BeginSendTo(byteData, 0, byteData.Length > 1024 ? 1024 : byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
bytes = new byte[1024];
clientSocket.BeginReceiveFrom(bytes, 0, 1024, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);
}
catch (Exception ex)
{
MessageBox.Show("Connection Error: " + ex.Message);
}
}
示例8: TestSendUDPToService
public string TestSendUDPToService(string ipaddress,int port)
{
Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
m_bufferManager = BufferManager.CreateBufferManager(100 * 1024, 1024);
for(int i =0 ;i<=50;i++)
{
AsyncClientToken asyncClientToken = new AsyncClientToken();
//asyncClientToken.HandlerReturnData = handlerReturnData;
asyncClientToken.Socket = socket;
//asyncClientToken.MessageID = messageID;
asyncClientToken.IP = ipaddress;
asyncClientToken.Port = port;
asyncClientToken.Buffer = m_bufferManager.TakeBuffer(1024);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(asyncClientToken.IP), asyncClientToken.Port);
int sendCount = Encoding.UTF8.GetBytes("TestSendUDPToService" + i.ToString(), 0, ("TestSendUDPToService" + i.ToString()).Length, asyncClientToken.Buffer, 0);
CommonVariables.LogTool.Log(DateTime.Now.ToString(CommonFlag.F_DateTimeFormat) + " Send:" + asyncClientToken.IP + asyncClientToken.Port.ToString() + "TestSendUDPToService" + i.ToString());
socket.BeginSendTo(asyncClientToken.Buffer, 0, sendCount, SocketFlags.None, ipe, new AsyncCallback(SendCallback), asyncClientToken);
}
return null;
}
示例9: event_ip
private void event_ip()
{
strName = util.globals.local_name;
ip = util.globals.popup_rep;
util.globals.popup_rep = null;
try
{
//Using UDP sockets
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
//IP address of the server machine
IPAddress ipAddress = IPAddress.Parse(ip);
//Server is listening on port 1000
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);
epServer = (EndPoint)ipEndPoint;
Client.Data msgToSend = new Client.Data ();
msgToSend.cmdCommand = Client.Command.Login;
msgToSend.strMessage = null;
msgToSend.strName = strName;
byte[] byteData = msgToSend.ToByte();
//Login to the server
clientSocket.BeginSendTo(byteData, 0, byteData.Length,
SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例10: Send
public void Send(string ip, int port, byte[] temp_sendbuffer)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.BeginSendTo(temp_sendbuffer, 0, temp_sendbuffer.Length, SocketFlags.None, (EndPoint)(new IPEndPoint(IPAddress.Parse(ip), port)), new AsyncCallback(SendTo_Callback), socket);
}
示例11: btnConnect_Click
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
this.name = txtName.Text.Trim();
// Initialise a packet object to store the data to be sent
Packet sendData = new Packet();
sendData.ChatName = this.name;
sendData.ChatMessage = null;
sendData.ChatDataIdentifier = DataIdentifier.LogIn;
// Initialise socket
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// Initialise server IP
IPAddress serverIP = IPAddress.Parse(txtServerIP.Text.Trim());
// Initialise the IPEndPoint for the server and use port 30000
IPEndPoint server = new IPEndPoint(serverIP, 30000);
// Initialise the EndPoint for the server
epServer = (EndPoint)server;
// Get packet as byte array
byte[] data = sendData.GetDataStream();
// Send data to server
clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epServer, new AsyncCallback(this.SendData), null);
// Initialise data stream
this.dataStream = new byte[1024];
// Begin listening for broadcasts
clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveData), null);
}
catch (Exception ex)
{
MessageBox.Show("Connection Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例12: btnConnect_Click
private void btnConnect_Click(object sender, EventArgs e)
{
/////////// Поиск ip клиента из DNS таблицы хоста
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
string ip = "";
for (int i = 0; i < host.AddressList.Length; i++)
{
ip = host.AddressList[i].ToString();
string pattern = @"\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?";
Regex regex = new Regex(pattern);
Match match = regex.Match(ip);
if (match.Success)
{
break;
}
}
try
{
// Initialise a packet object to store the data to be sent
Packet sendData = new Packet();
sendData.ChatMessage = null;
sendData.ChatDataIdentifier = DataIdentifier.LogIn;
// Initialise socket
if (clientSocket != null)
{
try
{
clientSocket.Close();
}
catch { }
}
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ClientIPE;
if (ip != "")
ClientIPE = new IPEndPoint(IPAddress.Parse(ip), 8080);
else
{
MessageBox.Show("Не удалось настроить ip адрес Клиента");
return;
}
clientSocket.Bind(ClientIPE);
IPAddress serverIP;
// Initialise server IP
if (txtIP.Text.Trim() != "")
serverIP = IPAddress.Parse(txtIP.Text.Trim());
else
{
MessageBox.Show("Введите ip адрес Сервера");
return;
}
// Initialise the IPEndPoint for the server and use port 30000
IPEndPoint server = new IPEndPoint(serverIP, 30000);
// Initialise the EndPoint for the server
epServer = (EndPoint)server;
// Get packet as byte array
byte[] data = sendData.GetDataStream();
// Send data to server
clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epServer, new AsyncCallback(this.SendData), null);
// Initialise data stream
this.dataStream = new byte[1024];
// Begin listening for broadcasts
clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveData), null);
}
catch (ObjectDisposedException)
{
MessageBox.Show("Не удалось подключиться к указанному серверу");
}
catch (ArgumentException) { }
catch (Exception ex)
{
try
{
clientSocket.Close();
}
catch { }
if (ex.Message == "Удаленный хост принудительно разорвал существующее подключение")
MessageBox.Show("Не удалось подключиться к серверу", "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show("Connection Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
示例13: sendCommand
void sendCommand(string _cmd)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] _byteData = Encoding.UTF8.GetBytes(_cmd);
IPAddress ip = IPAddress.Parse(Program.GetLocalIP4());
IPEndPoint ipEndPoint = new IPEndPoint(ip, Program.outputPort);
clientSocket.BeginSendTo(_byteData, 0, _byteData.Length, SocketFlags.None,
ipEndPoint, getResponseData, clientSocket);
}
示例14: button4_Click
private void button4_Click(object sender, EventArgs e)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
byte[] buffer=System.Text.Encoding.Unicode.GetBytes(textBox2.Text);
SendRes = socket.BeginSendTo(buffer, 0, buffer.Count(),
SocketFlags.None,
(EndPoint)new IPEndPoint(IPAddress.Parse("10.2.21.255"), 100),
new AsyncCallback(Send_Completed),
socket);
}
示例15: LoginForm_Load
private void LoginForm_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
try
{
//Server is listening on port 1000
foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
if (ip.AddressFamily == AddressFamily.InterNetwork)
IPHost = ip;
IPEndPoint _localEndPoint = new IPEndPoint(IPHost, 0);
IPEndPoint _ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 11000);
_findSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_findSocket.Bind(_localEndPoint);
_findSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
//_findSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);
epServer = (EndPoint)_ipEndPoint;
Data msgToSend = new Data();
msgToSend.cmdCommand = Command.ServerList;
msgToSend.strMessage = null;
msgToSend.strName = null;
_byteDataReg = msgToSend.ToByte();
//Find the servers
_findSocket.BeginSendTo(_byteDataReg, 0, _byteDataReg.Length,
SocketFlags.None, epServer, new AsyncCallback(OnSendReg), null);
_byteDataReg = new byte[1024];
//Start listening to the data asynchronously
_findSocket.BeginReceiveFrom(_byteDataReg,
0, _byteDataReg.Length,
SocketFlags.None,
ref epServer,
new AsyncCallback(OnReceiveReg),
null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
txtName.Text = "user" + (new Random(DateTime.Now.Millisecond).Next() % 89 + 10);
}