I tried to do a local chat program using UdpClient, no exception is thrown, it just does not get the message (I'm running 2 equal). My code:
public class UdpSenderReciver
{
int Port = 9600;
private static UdpClient udp;
static IPAddress address;
public static void Terminate()
{
udp.Close();
}
public UdpSenderReciver(int port = 9600)
{
Port = port;
if (udp != null)
return;
//address = new IPAddress(new byte[] {127,0,0,1});
address = IPAddress.Broadcast;
udp = new UdpClient("localhost", Port);
IPEndPoint ip = new IPEndPoint(address, Port);
udp.EnableBroadcast = true;
udp.Connect("localhost",Port);
//udp.Client.ReceiveTimeout = 1000;
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
//udp.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
}
//Sender
public void SendString(string message)
{
IPEndPoint ip = new IPEndPoint(address, Port);
byte[] bytes = Encoding.ASCII.GetBytes(message);
udp.Send(bytes, bytes.Length);
//udp.Close();
}
public void SendBufferedData(byte[] data)
{
IPEndPoint ip = new IPEndPoint(address, Port);
byte[] bytes = data;
udp.Send(bytes, bytes.Length);
//udp.Close();
}
//Reciver
byte[] result;
bool done = false;
void recive_data()
{
if (read_thread.IsAlive)
Debug.Log("Is alive");
done = false;
IPEndPoint ip = new IPEndPoint(address, Port);
byte[] data = null;
data = udp.Receive(ref ip);
result = data;
done = true;
read_thread.Abort();
}
Thread read_thread = null;
public byte[] ReciveBufferedData()
{
byte[] data = result;
if (read_thread == null)
{
read_thread = new Thread(recive_data);
}
if (!read_thread.IsAlive)
read_thread.Start();
if (done)
{
data = result;
done = false;
data = null;
}
return data;
}
public string ReciveString()
{
var data = ReciveBufferedData();
if (data == null)
return null;
return Encoding.UTF8.GetString(data);
}
}