美文网首页
猿学-基于Scala实现Socket和Server Socket

猿学-基于Scala实现Socket和Server Socket

作者: 猿学 | 来源:发表于2018-08-18 13:03 被阅读0次

    package MyResourceAndMyNodeManager

    import java.io.{ObjectInputStream, ObjectOutputStream}

    import java.net.{ServerSocket, Socket}

    object MyResourceManager {

      def handlerRegisterMsg(username: String, password: String): ResultMsg = {

        //对消息的处理

        println("username: " + username + "password: " + password)

        ResultMsg(1, "注册成功!!")

      }

      def handlerHeartbeat(hostname: String): ResultMsg = {

        println(hostname + "当前的时间:" + System.currentTimeMillis())

        ResultMsg(1, "心跳成功成功!!")

      }

      def main(args: Array[String]): Unit = {

        val serverSocket: ServerSocket = new ServerSocket(8888)

        val clientSocket: Socket = serverSocket.accept()

        val inputStream = new ObjectInputStream(clientSocket.getInputStream)

        val outputStream = new ObjectOutputStream(clientSocket.getOutputStream)

        while (true) {

          val clientMsg = inputStream.readObject()

          val result = clientMsg match {

            case RegisterMsg(username, password) => {

              //处理注册消息

              handlerRegisterMsg(username, password)

            }

            //

            case HeatBeart(hostname) => {

              handlerHeartbeat(hostname);

            }

          }

          //服务端要向客户端发送 结果消息

          outputStream.writeObject(result)

          outputStream.flush()

        }

      }

    }

    package MyResourceAndMyNodeManager

    import java.io.{ObjectInputStream, ObjectOutputStream}

    import java.net.Socket

    object MyNodeManager {

      def main(args: Array[String]): Unit = {

        val socket = new Socket("127.0.0.1", 8888)

        val outputStream = new ObjectOutputStream(socket.getOutputStream)

        val inputStream = new ObjectInputStream(socket.getInputStream)

        outputStream.writeObject(RegisterMsg("malaoshi", "malaoshi123"))

        outputStream.flush()

        //接收服务端传送来的消息

        val resultMsg = inputStream.readObject()

        println(" 我是客户端,我接收到了服务端传送过来的消息" + resultMsg)

        //向服务端发送心跳

        outputStream.writeObject(HeatBeart("hadoop1"))

        outputStream.flush()

        //接收服务端传送来的消息

        val resultMsg2 = inputStream.readObject()

        println(" 我是客户端,我接收到了服务端传送过来心跳的结果" + resultMsg2)

        outputStream.close()

        inputStream.close()

        socket.close()

      }

    }

    相关文章

      网友评论

          本文标题:猿学-基于Scala实现Socket和Server Socket

          本文链接:https://www.haomeiwen.com/subject/nfkfiftx.html