Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.net.{DatagramPacket, InetAddress, MulticastSocket, SocketTimeoutException}
- import java.lang.{Runnable, Thread}
- object TestUdpServer {
- class UdpServer(val address: String, val port: Int, val info: String) {
- val socket = new MulticastSocket(port)
- val multicastAddressGroup = InetAddress.getByName(address)
- socket.joinGroup(multicastAddressGroup)
- def execute: Unit = {
- while(true){
- val buffer = Array.ofDim[Byte](1024)
- val data = new DatagramPacket(buffer, buffer.length)
- try{
- socket.receive(data)
- checkMessage(new String(data getData).trim, info)
- }catch{
- case e:SocketTimeoutException => // nothing
- }
- }
- }
- private def checkMessage(msg: String, info: String): Unit = {
- if(msg == "QUERY") sendReply(info)
- }
- private def sendReply(info: String): Unit = {
- log("send reply")
- val response = ("REPLY:test-server:"+info+"++").getBytes
- socket.send(new DatagramPacket(response, response.length, multicastAddressGroup, port))
- }
- def log(msg: String): Unit = println("SERVER: " + msg)
- }
- def main(args: Array[String]): Unit = {
- new UdpServer("224.0.0.1",1234, args(0)).execute
- }
- }
Add Comment
Please, Sign In to add comment