public void Publish(Topic topic, byte[] content, bool retain, bool dup) { List <CoapOption> options = new List <CoapOption>(); byte[] nameBytes = Encoding.UTF8.GetBytes(topic.Name); options.Add(new CoapOption((int)CoapOptionType.URI_PATH, nameBytes.Length, nameBytes)); byte[] nodeIdBytes = Encoding.UTF8.GetBytes(_clientID); options.Add(new CoapOption((int)CoapOptionType.NODE_ID, nodeIdBytes.Length, nodeIdBytes)); byte[] qosValue = new byte[2]; qosValue[0] = 0x00; switch (topic.Qos) { case QOS.AT_LEAST_ONCE: qosValue[1] = 0x00; break; case QOS.AT_MOST_ONCE: qosValue[1] = 0x01; break; case QOS.EXACTLY_ONCE: qosValue[1] = 0x02; break; } options.Add(new CoapOption((int)CoapOptionType.ACCEPT, 2, qosValue)); CoapMessage coapMessage = new CoapMessage(VERSION, CoapType.CONFIRMABLE, CoapCode.PUT, 0, null, options, content); _timers.Store(coapMessage); //set message id = token id coapMessage.MessageID = Int32.Parse(Encoding.UTF8.GetString(coapMessage.Token)); _client.Send(coapMessage); }
void RunUDPClient(string hostAddress, bool sendRandomData) { UDPClient client = new UDPClient(hostAddress, this); client.Start(); client.Send("Hello World"); if (sendRandomData) { int waitTimeMilliseconds = 100; // call a generater in a different thread to send lots of numbers // at specified intervals Thread randomNumbersThread = new Thread(() => SendRandomNumbers(ref client, waitTimeMilliseconds)); randomNumbersThread.Start(); //if the user presses the key start trying to stop sending data Console.ReadKey(); Console.WriteLine("Preparing to stop sending data"); // stop the loop this.endFunction = false; // wait for a while to make sure your not stoping the thread some were important Thread.Sleep(waitTimeMilliseconds * 3); // 3 times the wait time should be more than enough } // Disconnect the client client.Disconnect(); Console.WriteLine("Program Stoped Sending Data"); }
/// <summary> /// Connect to the NAT hole punch server, this is called from a client machine /// </summary> /// <param name="host">The host address of the server the client is trying to connect to</param> /// <param name="port">The port number of the server the client is trying to connect to</param> /// <param name="clientPort">The port number that the client is listening on</param> /// <param name="natServer">The NAT server host address to connect to</param> /// <param name="natPort">The NAT server port number to connect to</param> public void Connect(string host, ushort port, ushort clientPort, string natServer, ushort natPort = DEFAULT_NAT_SERVER_PORT) { // Don't allow multiple NAT server connection requests at once if (Client != null) { return; } // Connect to the NAT server Client = new UDPClient(); Client.Connect(natServer, natPort, pendCreates: true); NetWorker.BaseNetworkEvent accepted = (NetWorker sender) => { // Send the data to the nat server with the host address and port that this client // is trying to connect to so that it can punch a hole in the network for this client JSONNode sendJson = JSONNode.Parse("{}"); sendJson.Add("host", new JSONData(host)); sendJson.Add("port", new JSONData(port)); sendJson.Add("clientPort", new JSONData(clientPort)); // Send the message to the NAT server Text connect = Text.CreateFromString(Client.Time.Timestep, sendJson.ToString(), false, Receivers.Server, MessageGroupIds.NAT_SERVER_CONNECT, false); Client.Send(connect, true); Client.messageConfirmed += (player, packet) => { if (packet.uniqueId == connect.UniqueId) { Client.Disconnect(false); } }; }; Client.serverAccepted += accepted; }
public void BidirectionalReceiving(double packetLoss) { UDPSocket.PACKET_LOSS = packetLoss; UDPServer <TestBehavior> server = GetServer <TestBehavior>(); server.Start(); UDPClient client = GetClient(); uint expected = 0; client.OnMessage += (s, d) => { uint num = BitConverter.ToUInt32(d.Data, 0); Assert.AreEqual(expected++, num); }; client.Connect(); for (uint i = 0; i < 10000; i++) { byte[] data = BitConverter.GetBytes(i); client.Send(data); } Thread.Sleep(1000); }
/// <summary> /// This program will send random numbers to a forign device /// using UDP packets. it will act as a client /// </summary> /// <param name="client"> /// A UDPObject Acting as the client to send data from /// </param> /// <param name="millisecondsBetweenIterations"> /// The time between sending data packets /// </param> void SendRandomNumbers(ref UDPClient client, int millisecondsBetweenIterations) { // a object to generate the random data to be sent Random randomGenerator = new Random(); // set veriable to true so the app runs this.endFunction = true; while (this.endFunction) { // this will be the data to send to the client string outputString = ""; // this loop will build the string to send to the other client for (int i = 0; i < 6; i++) { outputString += randomGenerator.Next(256); // add a deliminator to the items if (i < 5) { outputString += ","; } } Thread.Sleep(millisecondsBetweenIterations); // client.Send(outputString); } }
public void ServerReceiving(double packetLoss) { UDPSocket.PACKET_LOSS = packetLoss; UDPServer server = GetServer(); uint expected = 0; server.OnData += (ep, data) => { uint num = BitConverter.ToUInt32(data, 0); Assert.AreEqual(expected++, num); }; server.Start(); UDPClient client = GetClient(); client.Connect(); for (uint i = 0; i < 10000; i++) { byte[] data = BitConverter.GetBytes(i); client.Send(data); Thread.Sleep(0); } Thread.Sleep(1000); }
/// <summary> /// Registers a server to the NAT server so that it can be requested to be joined by clients /// </summary> /// <param name="currentPort">The current port that this server is listening for client connections on</param> /// <param name="natServer">The NAT server host address to connect to</param> /// <param name="natPort">The NAT server port number to connect to</param> public void Register(ushort currentPort, string natServer, ushort natPort = DEFAULT_NAT_SERVER_PORT) { // Don't allow multiple NAT server connection requests at once if (Client != null) { return; } // Connect to the NAT server Client = new UDPClient(); Client.Connect(natServer, natPort, pendCreates: true); // When connected, request for this server to be registered to the NAT lookup for clients NetWorker.BaseNetworkEvent accepted = (NetWorker sender) => { JSONNode obj = JSONNode.Parse("{}"); obj.Add("port", new JSONData(currentPort)); JSONClass sendJson = new JSONClass(); sendJson.Add("register", obj); // Send the message to the NAT server Text register = Text.CreateFromString(Client.Time.Timestep, sendJson.ToString(), false, Receivers.Target, MessageGroupIds.NAT_SERVER_REGISTER, false); Client.Send(register, true); }; Client.serverAccepted += accepted; // Setup the callback events for when clients attempt to join Client.textMessageReceived += PlayerConnectRequestReceived; }
public override bool Send(string data = "") { if (data == "") { return(false); } try { if (Status) { // sending the data to the linked implant byte[] databytes = Encoding.UTF8.GetBytes(data); UDPClient.Send(databytes, databytes.Length); } else { Console.WriteLine("The UDP link is not connected."); } return(true); } catch (Exception e) { Console.Error.WriteLine("UDP Client Exception on Send: " + e.Message); Status = false; // setting the status to false return(false); } }
/// <summary> /// Send data to another device via UDP /// </summary> public void SendStreamingData() { // update the content of the streaming data to be sent lock (SyncroLock) { uDPClient.Send(this.streamingData.ToString()); } }
public Client(int Port) { _UDP = new UDPClient(new IPEndPoint(IPAddress.Parse(Game_IP), Port), 0); _UDP.Send(new GMHelloPacket { Username = "******", Key = "KeyTest123", Version = "1.0" }); }
private void HandleNATTest(object sender, UdpDataReceivedEventArgs e) { var p = new Packet(e.Packet, 2); //_packetLogger.Log<ENATPacket>(p); uint addr; ushort port; Packet ack; switch (p.PacketID) { case (byte)ENATPacket.Req1: // test request addr = p.ReadUInt32(); port = p.ReadUInt16(); //_logger.Debug("-NAT Test- ID: {0} IP: {1} Port: {2} | {3}", p.PacketID, new IPAddress(addr), port, e.IPEndPoint.ToString()); ack = new Packet(ENATPacket.Ack1); ack.Write((uint)e.IPEndPoint.Address.Address); ack.Write((ushort)e.IPEndPoint.Port); _natServer.Send(e.IPEndPoint, ack); break; case (byte)ENATPacket.Req2: // firewall/nat type test addr = p.ReadUInt32(); port = p.ReadUInt16(); //_logger.Debug("-NAT Test- ID: {0} IP: {1} Port: {2} | {3}", p.PacketID, new IPAddress(addr), port, e.IPEndPoint.ToString()); ack = new Packet(ENATPacket.Ack2); ack.Write((uint)e.IPEndPoint.Address.Address); ack.Write((ushort)e.IPEndPoint.Port); _natServer2.Send(e.IPEndPoint, ack); break; case (byte)ENATPacket.KeepAlive: // keepalive? break; default: _logger.Warning("-NAT Test- ID: {0}", p.PacketID); break; } }
public async void Send(Serializable.Context3D context) { if (!udpClient.Active) { Debug.Log("[UDP] Sending packet failed. UDP client not active."); return; } // Debug.Log("[UDP] Sent packet (" + context.RigidBodies.Count + ")"); await udpClient.Send(context.ToByteArray()); // Debug.Log("[UDP] Sent context."); }
public void Connect(Action <int> OnConnect) { _OnConnect = OnConnect; _UDP = new UDPClient(new IPEndPoint(IPAddress.Parse(Client.Game_IP), Ports.Game_Start), 0); _UDP.OnReceivedPacket = OnReceivePacket; _UDP.Send(new GMHelloPacket { Username = "******", Key = "KeyTest123", Version = "1.0" }); _UDP.OnDisconnect = OnTimeout; }
private void HandleNATTest2(object sender, UdpDataReceivedEventArgs e) { var p = new Packet(e.Packet, 2); //_packetLogger.Log<ENATPacket>(p); switch (p.PacketID) { case (byte)ENATPacket.Req3: var addr = p.ReadUInt32(); var port = p.ReadUInt16(); //_logger.Debug("-NAT Test2- ID: {0} IP: {1} Port: {2} | {3}", p.PacketID, new IPAddress(addr), port, e.IPEndPoint.ToString()); var ack = new Packet(ENATPacket.Ack3); ack.Write((uint)e.IPEndPoint.Address.Address); ack.Write((ushort)e.IPEndPoint.Port); _natServer2.Send(e.IPEndPoint, ack); break; default: _logger.Warning("-NAT Test2- ID: {0}", p.PacketID); break; } }
/// <summary> /// /// </summary> void RunUDPDemoToms() { UDPClient client = new UDPClient(this); UDPListener listener = new UDPListener(NetworkingLibaryStandard.NetworkingLibaryStandard.DefaultPortNumber + 1, this); listener.Start(); client.Start(); client.Send("Hello World"); Console.ReadKey(); client.Disconnect(); listener.Stop(); }
static void Main(string[] args) { Console.WriteLine("server?y/n:"); string isServer = Console.ReadLine(); if (isServer.Equals("y")) { UDPBase udp = new UDPServer(2001); while (true) { } } else { Console.WriteLine("input usePort:"); string myPortText = Console.ReadLine(); Console.WriteLine("input name:"); string name = Console.ReadLine(); UDPClient udp = new UDPClient(int.Parse(myPortText), 2001, name); while (true) { Console.WriteLine("送信する文字列を入力してください。"); string sendMsg = Console.ReadLine(); if (sendMsg.Equals("test001")) { udp.Test001(); } else if (sendMsg.Equals("test002")) { udp.Test002(); } else { byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(sendMsg); udp.Send(sendBytes); } } } }
static void Main(string[] args) { Program program = new Program(); IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3001); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000); Console.WriteLine("CLIENT - " + localEP); client = new UDPClient(program); client.Start(localEP, remoteEP); while (true) { string line = Console.ReadLine(); client.Send(line, remoteEP); } }
public void ServerBehaviorReceiving(double packetLoss) { UDPSocket.PACKET_LOSS = packetLoss; UDPServer <TestBehavior> server = GetServer <TestBehavior>(); server.Start(); UDPClient client = GetClient(); client.Connect(); for (uint i = 0; i < 10000; i++) { byte[] data = BitConverter.GetBytes(i); client.Send(data); } Thread.Sleep(1000); }
/// <summary> /// /// </summary> public void StartSendingFromDataStore() { // this value will hold the next item to send off if it is valid string outputFromDS = ""; // keep getting data while it exists while (keepThreadRunning) { // if there is any output send it off or else wait a while if (this.DataManager.TryGetNext(out outputFromDS)) { Outlet.Send(outputFromDS); } else { // just wait a short while for data to pile up Thread.Sleep(millisecondsToWaitAfterFail); } } }
public GuestPass() { myServerConnection = new UDPClient(); base.HandleDestroyed += myServerConnection.OnExit; myServerConnection.AssignProcessor(delegate(Packet P) { FileDeletePacket myPacket = (FileDeletePacket)P; File.Delete("./Game/" + myPacket.myEntry.Location.Remove(0, 2)); }, typeof(FileDeletePacket)); myServerConnection.AssignProcessor(delegate(Packet P) { Action myAction = new Action(FailedToLogin); Status.Invoke(myAction); }, typeof(LoginFailedPacket)); myServerConnection.AssignProcessor(delegate(Packet P) { FileUpdatePacket myPacket = (FileUpdatePacket)P; Action myAction2; Action <int> myAction3 = new Action <int>(setTotal); Status.Invoke(myAction3, myPacket.TotalFiles); if (myPacket.TotalFiles == 0) { myAction2 = new Action(Finish); return; } else { myAction2 = new Action(incFinish); } String Data = Path.Combine("Game", myPacket.myEntry.GetDirectoryStripped()); Directory.CreateDirectory(Data.Remove(Data.LastIndexOf(Path.DirectorySeparatorChar))); File.WriteAllBytes(Data, myPacket.myBytes); Status.Invoke(myAction2); var myNextPacket = new GetNextFilePacket(); myNextPacket.Username = Username; myServerConnection.Send(myNextPacket, Lidgren.Network.NetDeliveryMethod.ReliableOrdered); }, typeof(FileUpdatePacket)); InitializeComponent(); }
private void LoginButton_Click(object sender, EventArgs e) { String Password = PasswordText.Text; Username = UsernameTextBox.Text; LoginUpdatePacket myLogin = new LoginUpdatePacket(); myLogin.CreateUsernamePasswordHash(Username, Password); Directory.CreateDirectory("./Game"); if (myHash != null && myHash.Count != 0) { myHash.Clear(); } RecurseIntoDirectory("./Game"); myLogin.myEntries = myHash; myAction3 = new Action(OnConnected); myServerConnection.OnConnect += LidgrenConnectedCallback; myAction4 = new Action(OnDisconnected); myServerConnection.Send(myLogin, Lidgren.Network.NetDeliveryMethod.ReliableOrdered); Status.Text = "Connecting!"; }
// Connect to the time server public void Connect() { try { IPAddress hostadd = DNS.Resolve(TimeServer); IPEndPoint EPhost = new IPEndPoint(hostadd, 123); UDPClient TimeSocket = new UDPClient(); TimeSocket.Connect(EPhost); Initialize(); TimeSocket.Send(NTPData, NTPData.Length); NTPData = TimeSocket.Receive(ref EPhost); if (!IsResponseValid()) { throw new Exception("Invalid response from " + TimeServer); } ReceptionTimestamp = DateTime.Now; } catch (SocketException e) { throw new Exception(e.Message); } }
private void button2_Click(object sender, EventArgs e) { string sSendUserData = textBox3.Text; // parse output data from textbox int numBytes = sSendUserData.Length / 2; byte [] sendIoData = new byte[numBytes]; textBox3.BackColor = Color.White; label4.Text = "OK"; if (sSendUserData.Length % 2 != 0) { textBox3.BackColor = Color.Red; label4.Text = "Odd number of characters given."; } else if (!IsValidHexString(sSendUserData)) { textBox3.BackColor = Color.Red; label4.Text = "Invalid characters given"; } else { for (int i = 0; i < sSendUserData.Length; i += 2) { string sByte = sSendUserData.Substring(i, 2); if (!byte.TryParse(sByte, System.Globalization.NumberStyles.HexNumber, null, out sendIoData[i / 2])) { textBox3.BackColor = Color.Red; label4.Text = "Parsing failed"; } } string sDat = String.Empty; for (int i = 0; i < numBytes; i++) { sDat += pack_usint(sendIoData[i]); // data } udp_client.Send(sDat); } }
public void Connect() { SetState(ConnectionState.CONNECTING); Boolean willPresent = false; if (_will != null) { willPresent = true; } SNConnect connect = new SNConnect(_isClean, _keepalive, _clientID, willPresent); if (_timers != null) { _timers.StopAllTimers(); } _timers = new TimersMap(this, _client, RESEND_PERIOND, _keepalive * 1000); _timers.StoreConnectTimer(connect); if (_client.IsConnected()) { _client.Send(connect); } }
private void SyncObject() { Console.WriteLine("Sending:{0}", (syncObject as ExampleObject).data); client.Send(serializer.Serialize <T>(syncObject)); }