[Host] May I ask how Netly can change the UDP receiver in real-time in Unity?I use server.Open(<host>)
changing IP
does not work.
#27
Answered
by
alec1o
1101728133
asked this question in
Q&A (Question and Answer)
-
For example, if the server is sending messages every second to 1.1.1.1, I would like to change it to 1.2.2.2 at this time |
Beta Was this translation helpful? Give feedback.
Answered by
alec1o
Dec 12, 2023
Replies: 1 comment 2 replies
-
using Netly;
using Netly.Core;
using System;
using UnityEngine;
public class UdpServerExample : MonoBehaviour
{
// unity side
public string ip = "127.0.0.1";
public int port = 12000;
private KeyCode reconnectKeyCode = KeyCode.Enter;
private Host host = null;
private bool useNewHost = false;
private UdpServer server = new UdpServer(false);
private void Awake()
{
server.OnOpen(() =>
{
print($"server: connection opened: {server.Host}");
// more stuff here...
});
server.OnData((client, buffer) =>
{
print($"server: receive data from ({client.Host}): {NE.GetString(buffer)}");
// more stuff here...
});
server.OnClose(() =>
{
if (useNewHost)
{
print($"server reconnecting: old ({server.Host}); new ({host});");
// reconnecting with new Host;
useNewHost = false; // set false because it is used
server.Open(host);
// return for not doing wrong on default behaviour
return;
}
print($"server: connection closed: {server.Host}");
// more stuff here...
});
}
private void Start()
{
host = new Host(ip, port);
server.Open(host);
}
private void Update()
{
if (Input.GetKeyDown(reconnectKeyCode))
{
ChangeHost(new Host(ip, port));
}
}
private void ChangeHost(Host newHost)
{
host = newHost;
useNewHost = true;
// it will close connection, on OnClose event it will reconnect with new host.
server.Close();
}
} It's working? |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
1101728133
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#25 (reply in thread)
server.Open
can't change host when connection is opened, because connection is already opened. use
server.Close
to netly stop bind old ip and port, after useserver.OnClose
to receive close connection notice, and onserver.OnClose
open connection again using newHost
instance and all will running perfectly.