Reputation: 131
i'm trying to make a networking script that will find all game servers on a LAN but i am running into some trouble; import System.Net.Sockets;
import System.Net.Sockets;
private var udp_server:UdpClient;
private var udp_client:UdpClient;
private var udp_port:int = 18000;
private var udp_broadcast_ip:IPAddress = IPAddress.Parse ("224.0.0.224");
private var selected:boolean = false;
private var udp_received_message:String;
function StartServer(){
udp_server = new UdpClient(udp_port, AddressFamily.InterNetwork);
var udp_endpoint:IPEndPoint = new IPEndPoint(udp_broadcast_ip, udp_port);
udp_server.Connect (udp_endpoint);
InvokeRepeating("StartBroadcastUDP", 0.0,0.3);
}
function StartClient(){
if(udp_client == null){
udp_client = new UdpClient(udp_port);
udp_client.BeginReceive(new AsyncCallback(StartReceiveUDP), null);
Debug.Log("Searching for udp");
}
}
function StartBroadcastUDP(){
var udp_broadcast_message:String = "GAME SERVER";
if(udp_broadcast_message != ""){
udp_server.Send(Encoding.ASCII.GetBytes (udp_broadcast_message), udp_broadcast_message.Length);
}
}
function StartReceiveUDP(result:IAsyncResult){
Debug.Log("Searching for udp");
var udp_endpoint:IPEndPoint = new IPEndPoint(IPAddress.Any, udp_port);
var udp_received_message_byte:byte[];
if(udp_client != null){
udp_received_message_byte = udp_client.EndReceive(result, udp_endpoint);
}else{
return;
}
udp_client.BeginReceive(new AsyncCallback(StartReceiveUDP), null);
udp_received_message = Encoding.ASCII.GetString(udp_received_message_byte);
Debug.Log("Searching for udp");
}
function Update(){
if(udp_received_message != null){
Debug.Log("Received Message: " + udp_received_message);
}
}
function OnGUI(){
if(!selected){
if(GUI.Button(Rect(0, 0, 50, 50), "Server")){
StartServer();
selected = true;
}else if(GUI.Button(Rect(50, 0, 50, 50), "Client")){
StartClient();
selected = true;
}
}
}
it seams that when i start receiving udp (BeginReceive in Startclient) it just plan doesn't to id. to make sure it is the case i added a few debug.logs and still got nothing
Upvotes: 1
Views: 371
Reputation: 875
Unfortunately async calls are somehow problematic in Unity. You can use blocking calls in threads or nonblocking calls in main thread (in Update methods).
Upvotes: 1