Guest User

Untitled

a guest
Jul 17th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. import java.net.{DatagramPacket, InetAddress, MulticastSocket, SocketTimeoutException}
  2. import java.lang.{Runnable, Thread}
  3.  
  4. object TestUdpServer {
  5. class UdpServer(val address: String, val port: Int, val info: String) {
  6. val socket = new MulticastSocket(port)
  7. val multicastAddressGroup = InetAddress.getByName(address)
  8. socket.joinGroup(multicastAddressGroup)
  9.  
  10. def execute: Unit = {
  11. while(true){
  12. val buffer = Array.ofDim[Byte](1024)
  13. val data = new DatagramPacket(buffer, buffer.length)
  14. try{
  15. socket.receive(data)
  16. checkMessage(new String(data getData).trim, info)
  17. }catch{
  18. case e:SocketTimeoutException => // nothing
  19. }
  20. }
  21. }
  22.  
  23. private def checkMessage(msg: String, info: String): Unit = {
  24. if(msg == "QUERY") sendReply(info)
  25. }
  26. private def sendReply(info: String): Unit = {
  27. log("send reply")
  28. val response = ("REPLY:test-server:"+info+"++").getBytes
  29. socket.send(new DatagramPacket(response, response.length, multicastAddressGroup, port))
  30. }
  31. def log(msg: String): Unit = println("SERVER: " + msg)
  32. }
  33.  
  34. def main(args: Array[String]): Unit = {
  35. new UdpServer("224.0.0.1",1234, args(0)).execute
  36. }
  37. }
Add Comment
Please, Sign In to add comment