Udpclient not receiving

Asked

Viewed 32 times

0

I tried to make a local chat program using Udpclient, no exception is thrown, it just doesn’t 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);
}
}
  • Everyone on the same door and without any host?

  • @Leandroangelo I edited the question, now with host in the code

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.