UDP Listener c#

2019-08-23 06:39发布

I asked a query this morning, here is the link - thread interrupt in udp

but after spending some more hours on this issue - I have concluded that what I need to do is -

I need to create a udp server whose job is to listen and receive data from port 1200. and I need to create another udp socket to send data using any other port.

I want this udp listener to listen continuously as a background process. so I tried to do that but I am getting this error - and more over the statement is saying when sending data using sendto method even I am not sending any data here.

"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied"

  StackTrace  "   at System.Net.Sockets.Socket.get_RemoteEndPoint()"  string
  SocketErrorCode NotConnected    System.Net.Sockets.SocketError

I used this code for receiving on port 1200 with any remote client-

  public void button1_Click()
    {
        this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        this.serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        this.serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
        EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
        this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, serverSocket);

    }

    private void DoReceiveFrom(IAsyncResult iar)
    {


        try
        {
            EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);

            int dataLen = 0;
            byte[] data = null;
            try
            {
                dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
                data = new byte[dataLen];
                Array.Copy(this.byteData, data, dataLen);
                string ips = ((IPEndPoint)clientEP).Address.ToString();
                server sss = new server();
                sss.updateData(data, ips);
            }
            catch (Exception e)
            {
            }
            finally
            {
                EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
                this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, serverSocket);
            }

            if (!this.clientList.Any(client => client.Equals(clientEP)))
                this.clientList.Add(clientEP);



            string s = Encoding.ASCII.GetString(data);


        }
        catch (Exception ex)
        {
            string m = ex.Message;
        }
    }

    public void Stop()
    {
        this.serverSocket.Close();
        this.serverSocket = null;
        this.clientList.Clear();
    }

what should I do now? MY problem is this now - I just want to get whatever and whenever 1200 receives data and find the remote ip from that and then do some task . I have had examples for doing something like this but they are on TCP and TCP connects to each device but UDP does not.

So how can I do with udp.?

Here is the code updated -

  static void OnUdpData(IAsyncResult result)
    {
        // this is what had been passed into BeginReceive as the second parameter:
        UdpClient socket = result.AsyncState as UdpClient;
        // points towards whoever had sent the message:
        IPEndPoint source = new IPEndPoint(0, 0);
        // get the actual message and fill out the source:
        byte[] message = socket.EndReceive(result, ref source);
        string ip = source.Address.ToString();
        server cs = new server();
        cs.updateData(message, ip);

        socket.BeginReceive(new AsyncCallback(OnUdpData), socket);
    }
    public static void ReceiveData()
    {
        UdpClient socket = new UdpClient(1200); 
        socket.BeginReceive(new AsyncCallback(OnUdpData), socket);


    }

this is working with console app but not in web form. Its throwing error as Socket can be used 1 time.

So I changed a bit more lines like this -

public static void ReceiveData()
    {
        IPEndPoint iPEnd = new IPEndPoint(IPAddress.Any, 1200);
        UdpClient socket = new UdpClient(iPEnd);
        EndPoint ep = iPEnd;
        socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
        socket.Client.Bind(ep);
        socket.BeginReceive(new AsyncCallback(OnUdpData), socket);
    }

but this is also giving error. So why is this happening? If the code can work in console app then why not in web form?

标签: asp.net udp
0条回答
登录 后发表回答