B4J Question [SOLVED} upnp server / discovery

madru

Active Member
Licensed User
Longtime User
hi, I found this code in an old thread.....

can somebody explain how to reply via the socket/connection?



B4X:
Sub Process_Globals
   Private udp As UDPSocket
End Sub

Sub AppStart (Args() As String)
   CreateMulticastSocket("udp", 1900, "239.255.255.250")
   StartMessageLoop
End Sub

Sub CreateMulticastSocket (EventName As String, Port As Int, Group As String)
   Dim multi As JavaObject
   multi.InitializeNewInstance("java.net.MulticastSocket", Array(Port))
   Dim inet As JavaObject
   multi.RunMethod("joinGroup", Array(inet.InitializeStatic("java.net.InetAddress").RunMethod("getByName", Array(Group))))
   Dim jo As JavaObject = Me
   jo.RunMethod("SetMulticastSocket", Array(EventName, multi, udp))
End Sub

Sub udp_PacketArrived (Packet As UDPPacket)
    Dim msg As String
    msg = BytesToString(Packet.Data, Packet.Offset, Packet.Length, "UTF8")
   
    Dim s As String = "M-SEARCH * HTTP/1.1" & Chr(13) & Chr(10) &    _
        "HOST: 239.255.255.250:1900" & Chr(13) & Chr(10) &    _
        "ST: upnp:rootdevice" & Chr(13) & Chr(10) &    _
        "MAN: ""ssdp:discover""" & Chr(13) & Chr(10) &    _
        "MX: 3" & Chr(13) & Chr(10) & Chr(13) & Chr(10)
   
    If msg = s Then ' check for"MAN: "ssdp:discover"?
       
        Dim reply As String = "HTTP/1.1 200 OK" & Chr(13) & Chr(10) &    _
            "DATE: Wed, 16 Jun 2021 07:34:58 GMT" & Chr(13) & Chr(10) &    _
            "ST: upnp:rootdevice" & Chr(13) & Chr(10) &    _
            "EXT:" & Chr(13) & Chr(10) &    _
            "USN: uuid:aa3f61cff-a657-829d-7a3a-d91acabd0dd::upnp:rootdevice" & Chr(13) & Chr(10) &    _
            "LOCATION: http://192.168.1.2:1234/upnp/index.xml" & Chr(13) & Chr(10) &    _
            "CACHE-CONTROL: max-age=1800" & Chr(13) & Chr(10) &    _
            "SERVER: MY-SERVER"&Chr(13) & Chr(10) &    _
            "X-MY-NAME: MY-SERVER-NAME" & Chr(13) & Chr(10) & Chr(13) & Chr(10)
   
        'send reply (answer) how?

    End If

End Sub


#if java
import java.net.*;
public static void SetMulticastSocket (String EventName, MulticastSocket socket, anywheresoftware.b4a.objects.SocketWrapper.UDPSocket udp) {
   udp.init(ba, EventName, 8192, socket);
}
#end if
 

madru

Active Member
Licensed User
Longtime User
all good, typo mistake

I have UDPSocket & UDPSocket1, used the wrong one :(

B4X:
        Dim data() As Byte
        data = answer.GetBytes("UTF8")
        Packet.Initialize(data,Packet.HostAddress, 5000)
        UDPSocket1.Send(Packet)
 
Upvote 0
Top