首页 > 程序开发 > 软件开发 > java教程 > java高级教程 >

基于Scala实现Socket和Server Socket代码

2018-04-26

基于Scala实现Socket和Server Socket代码package MyResourceAndMyNodeManagerimport java io {ObjectInputStream, ObjectOutputStream} import java net {ServerSocket, Socket}ob

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()

  }
}


相关文章
最新文章
热点推荐