private void BeginReceive(UDPSocket socket) { if (_running == 0) return; if (socket.ReadBuffer.RemoteEndPoint == null) { socket.ReadBuffer.RemoteEndPoint = socket.Socket.Connected ? socket.Socket.RemoteEndPoint : new IPEndPoint(socket.Socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); } Boolean willRaiseEvent; try { willRaiseEvent = socket.Socket.ReceiveFromAsync(socket.ReadBuffer); } catch (ObjectDisposedException) { // do nothing return; } catch (Exception ex) { EndReceive(socket, ex); return; } if (!willRaiseEvent) { ProcessReceive(socket.ReadBuffer); } }
public static int Main(string[] args) { int port = 0; if (args.Length < 1 || !int.TryParse(args[0], out port)) port = 14000; uint bufferSize = 0; if (args.Length < 2 || !uint.TryParse(args[1], out bufferSize)) bufferSize = 1024; UDPSocket udpSocket = new UDPSocket(port, bufferSize); udpSocket.OnReceived += (byte[] message, IPEndPoint receiver) => { udpSocket.SendTo(message, receiver); // Console.WriteLine("received: {0}", BitConverter.ToInt64(arg2, 0)); }; udpSocket.Start(); while (Console.ReadLine() != "quit") { } udpSocket.Stop(); return 0; }
private void BeginSend(UDPSocket socket, Byte[] data, System.Net.EndPoint destination) { socket.SetWriteBuffer(data, 0, data.Length); socket.WriteBuffer.RemoteEndPoint = destination; Boolean willRaiseEvent; try { willRaiseEvent = socket.Socket.SendToAsync(socket.WriteBuffer); } catch (ObjectDisposedException) { // do nothing return; } catch (Exception ex) { EndSend(socket, ex); return; } if (!willRaiseEvent) { ProcessSend(socket.WriteBuffer); } }
private void BeginSend(UDPSocket socket, Byte[] data, System.Net.EndPoint destination) { try { socket.Socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, destination, SendCallback, socket); } catch (ObjectDisposedException) { // do nothing } catch (Exception ex) { EndSend(socket, ex); } }
public IPhone_utilityViewController() : base("IPhone_utilityViewController", null) { latencyQueue = new Queue<long>(); udpSocket = new UDPSocket(0, 1024); udpSocket.OnReceived = (receiveBuffer, endPoint) => { long received = BitConverter.ToInt64(receiveBuffer, 0); var latency = DateTime.Now.Ticks - received; // Console.WriteLine(DateTime.FromBinary(latency).Millisecond); lock (latencyQueue) { latencyQueue.Enqueue(latency); } }; }
private void BeginReceive(UDPSocket socket) { if (_running == 0) return; System.Net.EndPoint remoteEP = new IPEndPoint( socket.Socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); try { socket.Socket.BeginReceiveFrom(socket.Buffer, 0, socket.Buffer.Length, SocketFlags.None, ref remoteEP, ReceiveCallback, socket); } catch (ObjectDisposedException) { // do nothing } catch (Exception ex) { EndReceive(socket, ex); } }
/// <inheritdoc/> public void Start() { if (System.Threading.Interlocked.CompareExchange(ref _running, 1, 0) > 0) { return; } if (_localEP == null) { try { _socket = SetupUDPSocket(AddressFamily.InterNetworkV6, _receivePacketSize + 1); // +1 to check for > ReceivePacketSize } catch (SocketException e) { if (e.SocketErrorCode == SocketError.AddressFamilyNotSupported) { _socket = null; } else { throw e; } } if (_socket == null) { // IPv6 is not supported, use IPv4 instead _socket = SetupUDPSocket(AddressFamily.InterNetwork, _receivePacketSize + 1); _socket.Socket.Bind(new IPEndPoint(IPAddress.Any, _port)); } else { try { // Enable IPv4-mapped IPv6 addresses to accept both IPv6 and IPv4 connections in a same socket. _socket.Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0); } catch { // IPv4-mapped address seems not to be supported, set up a separated socket of IPv4. _socketBackup = SetupUDPSocket(AddressFamily.InterNetwork, _receivePacketSize + 1); } _socket.Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port)); if (_socketBackup != null) { _socketBackup.Socket.Bind(new IPEndPoint(IPAddress.Any, _port)); } } } else { _socket = SetupUDPSocket(_localEP.AddressFamily, _receivePacketSize + 1); _socket.Socket.Bind(_localEP); } if (_receiveBufferSize > 0) { _socket.Socket.ReceiveBufferSize = _receiveBufferSize; if (_socketBackup != null) { _socketBackup.Socket.ReceiveBufferSize = _receiveBufferSize; } } if (_sendBufferSize > 0) { _socket.Socket.SendBufferSize = _sendBufferSize; if (_socketBackup != null) { _socketBackup.Socket.SendBufferSize = _sendBufferSize; } } BeginReceive(); }
private void EndSend(UDPSocket socket, Exception ex) { // TODO may log exception? BeginSend(); }
static void Main(string[] args) { if (args.Length < 2) { show_usage(); return; } string server_ip; int port_server; int port_client; if (!args[0].Contains(":")) { show_usage(); Console.WriteLine("Bad server:port"); return; } string[] server_and_port = args[0].Split(':'); server_ip = server_and_port[0]; if (!Int32.TryParse(server_and_port[1], out port_server)) { show_usage(); Console.WriteLine("Bad server port"); return; } if (!Int32.TryParse(args[1], out port_client)) { show_usage(); Console.WriteLine("Bad listen port"); return; } UDPSocket s = new UDPSocket(); s.Server(port_server); s.debug = false; UDPSocket c = new UDPSocket(); c.Client(server_ip, port_client); c.debug = false; while (true) { var key = Console.ReadKey(); //Debug.WriteLine("Send key: {0}", (int)key.KeyChar); if (key.Key == ConsoleKey.Enter) { c.Send("\n"); Console.WriteLine(); } else { c.Send(key.KeyChar.ToString()); } } }
private void EndReceive(UDPSocket socket, Exception ex) { BeginReceive(socket); }
private void EndSend(UDPSocket socket, Exception ex) { BeginSend(); }
public void Dispose() { UDPSocket.Dispose(); }
public void Stop() { if (System.Threading.Interlocked.Exchange(ref _Running, 0) == 0) return; if (_Socket != null) { _Socket.Dispose(); _Socket = null; } if (_SocketIPv4 != null) { _SocketIPv4.Dispose(); _SocketIPv4 = null; } }
private void EndSend(UDPSocket socket, Int32 bytesTransferred) { BeginSend(); }
private void EndReceive(UDPSocket socket, Byte[] buffer, Int32 offset, Int32 count, System.Net.EndPoint ep) { if (count > 0) { Byte[] bytes = new Byte[count]; Buffer.BlockCopy(buffer, 0, bytes, 0, count); if (ep.AddressFamily == AddressFamily.InterNetworkV6) { IPEndPoint ipep = (IPEndPoint)ep; if (IPAddressExtensions.IsIPv4MappedToIPv6(ipep.Address)) ep = new IPEndPoint(IPAddressExtensions.MapToIPv4(ipep.Address), ipep.Port); } FireDataReceived(bytes, ep); } BeginReceive(socket); }
/// <inheritdoc/> public void Start() { if (System.Threading.Interlocked.CompareExchange(ref _running, 1, 0) > 0) return; if (_localEP == null) { try { _socket = SetupUDPSocket(AddressFamily.InterNetworkV6, _receivePacketSize + 1); // +1 to check for > ReceivePacketSize } catch (SocketException e) { if (e.SocketErrorCode == SocketError.AddressFamilyNotSupported) _socket = null; else throw e; } if (_socket == null) { // IPv6 is not supported, use IPv4 instead _socket = SetupUDPSocket(AddressFamily.InterNetwork, _receivePacketSize + 1); _socket.Socket.Bind(new IPEndPoint(IPAddress.Any, _port)); } else { try { // Enable IPv4-mapped IPv6 addresses to accept both IPv6 and IPv4 connections in a same socket. _socket.Socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0); } catch { // IPv4-mapped address seems not to be supported, set up a separated socket of IPv4. _socketBackup = SetupUDPSocket(AddressFamily.InterNetwork, _receivePacketSize + 1); } _socket.Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port)); if (_socketBackup != null) _socketBackup.Socket.Bind(new IPEndPoint(IPAddress.Any, _port)); } } else { _socket = SetupUDPSocket(_localEP.AddressFamily, _receivePacketSize + 1); _socket.Socket.Bind(_localEP); } if (_receiveBufferSize > 0) { _socket.Socket.ReceiveBufferSize = _receiveBufferSize; if (_socketBackup != null) _socketBackup.Socket.ReceiveBufferSize = _receiveBufferSize; } if (_sendBufferSize > 0) { _socket.Socket.SendBufferSize = _sendBufferSize; if (_socketBackup != null) _socketBackup.Socket.SendBufferSize = _sendBufferSize; } BeginReceive(); }
private void EndReceive(UDPSocket socket, Exception ex) { // TODO may log exception? BeginReceive(socket); }
public static void Bind(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { socket = new UDPSocket(localEndPoint, remoteEndPoint); }
// Start is called before the first frame update void Start() { serverSock = new UDPSocket(); serverSock.Server("127.0.0.1", 50090); //serverSock.Send("Received") }
/// <summary> /// Creates a new UDP cookie /// </summary> /// <param name="socket">The socket</param> public UDPSocketCookie(UDPSocket socket) { Socket = socket; }
public void IniciarServer() { s = new UDPSocket(); qr.Generate_QR(); s.init(Port, trackerInfo, 60000, 15); }
private void BeginReceive(UDPSocket socket) { #if LOG_UDP_CHANNEL _Log.Debug(m => m("BeginReceive: socket={0} _running={1}", socket.Socket.LocalEndPoint, _running)); #endif if (_running == 0) { return; } if (socket.ReadBuffer.RemoteEndPoint == null) { socket.ReadBuffer.RemoteEndPoint = socket.Socket.Connected ? socket.Socket.RemoteEndPoint : new IPEndPoint(socket.Socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); #if LOG_UDP_CHANNEL _Log.Debug(m => m("BeginReceive: Setup the remote endpoint {0}", socket.ReadBuffer.RemoteEndPoint.ToString())); #endif } bool willRaiseEvent; try { #if LOG_UDP_CHANNEL _Log.Debug("BeginReceive: Start async read"); #endif if (UseReceiveMessageFrom) { willRaiseEvent = socket.Socket.ReceiveMessageFromAsync(socket.ReadBuffer); } else { willRaiseEvent = socket.Socket.ReceiveFromAsync(socket.ReadBuffer); } } catch (NotImplementedException) { UseReceiveMessageFrom = false; willRaiseEvent = socket.Socket.ReceiveFromAsync(socket.ReadBuffer); } catch (ObjectDisposedException) { #if LOG_UDP_CHANNEL _Log.Debug(m => m("BeginRecieve: Socket {0} is disposed", socket.ToString())); #endif // do nothing return; } catch (Exception ex) { #if LOG_UDP_CHANNEL _Log.Debug(m => m("BeginReceive: Socket {0} has exception", socket.ToString())); #endif EndReceive(socket, ex); return; } #if LOG_UDP_CHANNEL _Log.Debug(m => m("BeginReceive: willRaiseEvent={0}", willRaiseEvent)); #endif if (!willRaiseEvent) { ProcessReceive(socket.ReadBuffer); } }
/// <inheritdoc/> public void Stop() { if (System.Threading.Interlocked.Exchange(ref _running, 0) == 0) return; if (_socket != null) { _socket.Dispose(); _socket = null; } if (_socketBackup != null) { _socketBackup.Dispose(); _socketBackup = null; } }
void ClientInterface(Socket client, byte index) { //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); Client mecl = clients[index]; { //client notify block // ushort len|com|ushort len|udp addr client.Send(new byte[] { 0x1, 0x0, 0x1, 0x1, 0x0, index }); // 0000 0001 (0x1) - (TCP) flag, set address } byte[] TCPhead_buffer = new byte[5]; byte[] unicast_addr = new byte[1]; ushort readbytes; byte[] temp_buffer; byte[] indexstate = new byte[] { 1, 0, 3, 1, 0, 0 }; ushort msize; Client tclient; Dictionary <byte, UDPacket> .Enumerator timedudp_enum; bool nwaitsend = true; Stopwatch stw = new Stopwatch(); uint my_time = time; try { do { stw.Restart(); while (client.Available != 0) { readbytes = (ushort)client.Receive(TCPhead_buffer); if (readbytes == 5) { if (TCPhead_buffer[0] == TCPhead_buffer[3] && TCPhead_buffer[1] == TCPhead_buffer[4]) { switch (TCPhead_buffer[2] & 0xF) { case 0: msize = BitConverter.ToUInt16(TCPhead_buffer, 0); temp_buffer = new byte[msize + 5]; TCPhead_buffer.CopyTo(temp_buffer, 0); client.Receive(temp_buffer, 5, msize, SocketFlags.None); mecl.protocols.tcp.broadcast.Add(temp_buffer); //Console.WriteLine("[" + index + " -> all] data: " + Encoding.ASCII.GetString(temp_buffer, 5, msize)); break; case 2: msize = BitConverter.ToUInt16(TCPhead_buffer, 0); client.Receive(unicast_addr); temp_buffer = new byte[msize + 5]; TCPhead_buffer.CopyTo(temp_buffer, 0); client.Receive(temp_buffer, 6, msize - 1, SocketFlags.None); temp_buffer[5] = index; clients[unicast_addr[0]].protocols.tcp.unicast.Add(temp_buffer); //Console.WriteLine("[" + index + " -> " + unicast_addr[0] + "] data: " + Encoding.ASCII.GetString(temp_buffer, 6, msize - 1)); break; case 3: client.Receive(unicast_addr); indexstate[5] = clients[unicast_addr[0]].active ? (byte)1 : (byte)0; mecl.protocols.tcp.unicast.Add(indexstate); //Console.WriteLine("[" + index + " -> " + index + "] indexState: " + indexstate[5]); break; case 1: byte[] indexes = new byte[clients.Count(n => n.active == true) + 4]; ushort cpos = 5; BitConverter.GetBytes((ushort)(indexes.Length - 5)).CopyTo(indexes, 0); indexes[3] = indexes[0]; indexes[4] = indexes[1]; indexes[2] = 1; for (ushort i = 0; i != clients.Count; ++i) { if (i != index && clients[i].active) { indexes[cpos++] = (byte)i; } } mecl.protocols.tcp.unicast.Add(indexes); //Console.WriteLine("[" + index + " -> " + index + "] indexes: " + string.Join("", indexes.Select(n => n.ToString() + ",").ToArray<string>(), 5, indexes.Length - 5)); break; case 4: mecl.protocols.udp.sendertime = 0; //Console.WriteLine("[" + index + " -> con] action: reset sender counter"); break; } } else { throw new SocketException(10054); } } else { throw new SocketException(10054); } } if (time != my_time) { mecl.notsent = true; ClientInterfaceThSend(); waitPacketSend.WaitOne(); nwaitsend = false; for (ushort i = 0; i != mecl.protocols.tcp.unicast.Count; ++i) { client.Send(mecl.protocols.tcp.unicast[i]); } if (mecl.protocols.udp.actualIP != null) { for (ushort i = 0; i != clients.Count; ++i) { if (i != index && clients[i].active) { tclient = clients[i]; for (ushort i1 = 0; i1 != tclient.protocols.tcp.broadcast.Count; ++i1) { client.Send(tclient.protocols.tcp.broadcast[i1]); } timedudp_enum = tclient.protocols.udp.broadcast_timed.GetEnumerator(); do { UDPSocket.SendTo(timedudp_enum.Current.Value.data, mecl.protocols.udp.actualIP); } while (timedudp_enum.MoveNext()); for (ushort i1 = 0; i1 != tclient.protocols.udp.broadcast_stand.Count; ++i1) { UDPSocket.SendTo(tclient.protocols.udp.broadcast_stand[i1].data, mecl.protocols.udp.actualIP); } } } timedudp_enum = mecl.protocols.udp.unicast_timed.GetEnumerator(); do { UDPSocket.SendTo(timedudp_enum.Current.Value.data, mecl.protocols.udp.actualIP); } while (timedudp_enum.MoveNext()); for (ushort i = 0; i != mecl.protocols.udp.unicast_stand.Count; ++i) { UDPSocket.SendTo(mecl.protocols.udp.unicast_stand[i].data, mecl.protocols.udp.actualIP); } } else { for (ushort i = 0; i != clients.Count; ++i) { if (i != index && clients[i].active) { tclient = clients[i]; for (ushort i1 = 0; i1 != tclient.protocols.tcp.broadcast.Count; ++i1) { client.Send(tclient.protocols.tcp.broadcast[i1]); } } } } nwaitsend = true; my_time = time; mecl.notsent = false; ClientInterfaceClear(); waitPacketClear.WaitOne(); } stw.Stop(); if (stw.ElapsedMilliseconds < 20) { Thread.Sleep((int)(20 - stw.ElapsedMilliseconds)); } } while (client.Connected); throw new SocketException(10054); } catch { stw.Stop(); while (true) { if (time != my_time) { if (nwaitsend) { mecl.notsent = true; ClientInterfaceThSend(); waitPacketSend.WaitOne(); } mecl.notsent = false; ClientInterfaceClear(); waitPacketClear.WaitOne(); mecl.protocols.udp.actualIP = null; mecl.active = false; client.Shutdown(SocketShutdown.Both); client.Close(); break; } else { Thread.Sleep(20); } } } }
static void Main(string[] args) { String path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "password.txt"); String contents = File.ReadAllText(path); Console.WriteLine($"Succesflly got private data:\r\n{contents}"); //Add 17 bytes more to guaranteely send 2 or more packets //Now split by 17 bytes each int ctr = 0; List <byte[]> pcs = new List <byte[]>(); int BYTE_CNT = 17; byte[] current = new byte[BYTE_CNT]; if (contents.Length % 17 != 0) { String temp = "------------------"; contents = contents + temp.Substring(0, 17 - contents.Length % 17); } ; foreach (var cb in Encoding.ASCII.GetBytes(contents)) { if (ctr == BYTE_CNT - 1) { byte[] bf = new byte[BYTE_CNT]; current.CopyTo(bf, 0); pcs.Add(bf); String deb = Encoding.ASCII.GetString(bf); ctr = 0; for (int i = 0; i < BYTE_CNT; i++) { current[i] = 0x0; } } if (cb == '\n' || cb == '\r') { current[ctr] = Encoding.ASCII.GetBytes("_")[0]; } else { current[ctr] = cb; } ctr++; } //OK split Console.WriteLine($"OK split into {pcs.Count} parts"); //Now send var ip = ReadLine("0.0.0.0", $"Enter server IP [0.0.0.0]: "); int port = int.Parse(ReadLine("123", "Enter port to server on [123]: ")); UDPSocket socket = new UDPSocket(); socket.Client(ip, port); byte pkt_id = 0; int total_sent = 0; Stopwatch sw = new Stopwatch(); sw.Start(); foreach (var ci in pcs) { NtpPacket ntp = new NtpPacket(); ntp = ntp.EmbedDataToPacketC(ci); byte[] result = ntp.BuildPacket(); result[5] = pkt_id; packets.Add(pkt_id, result); socket.Send(result); Thread.Sleep(200); total_sent += result.Length; pkt_id++; } sw.Stop(); Console.WriteLine($"Sent {pkt_id} packets in {sw.ElapsedMilliseconds} ms. Avg speed: {total_sent / ((double)((double)sw.ElapsedMilliseconds / (double)1000))} B/s"); Console.WriteLine("Finised. Press any key to close..."); Console.ReadKey(true); }
public void Start() { if (System.Threading.Interlocked.CompareExchange(ref _Running, 1, 0) > 0) return; if (_LocalEndPoint == null) { try { _Socket = SetupUDPSocket(AddressFamily.InterNetworkV6, _ReceivePacketSize + 1); // +1 to check for > ReceivePacketSize } catch (SocketException e) { if (e.SocketErrorCode == SocketError.AddressFamilyNotSupported) _Socket = null; else throw e; } if (_Socket == null) { // IPv6 is not supported, use IPv4 instead _Socket = SetupUDPSocket(AddressFamily.InterNetwork, _ReceivePacketSize + 1); _Socket.Socket.Bind(new IPEndPoint(IPAddress.Any, _Port)); } else { _SocketIPv4 = SetupUDPSocket(AddressFamily.InterNetwork, _ReceivePacketSize + 1); _Socket.Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _Port)); if (_SocketIPv4 != null) _SocketIPv4.Socket.Bind(new IPEndPoint(IPAddress.Any, _Port)); } } else { _Socket = SetupUDPSocket(_LocalEndPoint.AddressFamily, _ReceivePacketSize + 1); _Socket.Socket.Bind(_LocalEndPoint); } if (_ReceiveBufferSize > 0) { _Socket.Socket.ReceiveBufferSize = _ReceiveBufferSize; if (_SocketIPv4 != null) _SocketIPv4.Socket.ReceiveBufferSize = _ReceiveBufferSize; } if (_SendBufferSize > 0) { _Socket.Socket.SendBufferSize = _SendBufferSize; if (_SocketIPv4 != null) _SocketIPv4.Socket.SendBufferSize = _SendBufferSize; } BeginReceive(); }