设为首页 加入收藏

TOP

基于Scala实现Socket和Server Socket代码
2018-04-27 06:04:00 】 浏览:25
Tags:基于 Scala 实现 Socket Server 代码
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()

  }
}



编程开发网
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇java (bitmap bitvector)的解析.. 下一篇MySQL下perror工具查看System Err..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

最新文章

热门文章

C 语言

C++基础

windows编程基础

linux编程基础

C/C++面试题目