知识点概述
- 序列化反序列化
- Socket 网络通信
- Scala 函数式编程
- 输入输出流操作
1. Sender (客户端)
object sender {
def main(args: Array[String]): Unit = {
val socket = new Socket("localhost", 8848)
val objectOut = new ObjectOutputStream(socket.getOutputStream)
val task = new Task()
def op(x: Int, y:Int) : Int = {
x + y
}
task.setValue1(522)
task.setValue2(123)
task.setOp(op)
//写对象到Socket
objectOut.writeObject(task)
// 刷新
objectOut.flush()
println("Task 发送到 processor ...")
//关闭输出流
socket.shutdownOutput()
//接收
val objectInput = new ObjectInputStream(socket.getInputStream())
val obj = objectInput.readObject()
val responseTask = obj.asInstanceOf[Task]
//输出计算结果
println("sender 收到的结果是:" + responseTask.result)
//关闭流
objectInput.close()
objectOut.close()
socket.close()
}
}
2. Processor 服务端
object processor {
def main(args: Array[String]): Unit = {
val serverSocket = new ServerSocket(8848)
val socket = serverSocket.accept()
println("processor 收到 Task, 处理 Task ...")
val objectInput = new ObjectInputStream(socket.getInputStream())
val obj = objectInput.readObject()
val task = obj.asInstanceOf[Task]
println("处理器处理完毕, 计算的结果是: " + task.op(3, 4))
val res = task.op(3, 4)
//计算完结果给 task 设置
task.setResult(res)
val objectOut = new ObjectOutputStream(socket.getOutputStream)
//写对象到Socket
objectOut.writeObject(task)
// 刷新
objectOut.flush()
//关闭 ObjectOutputStream
objectOut.close()
socket.close()
}
}
3. 传输的 Task
class Task extends Serializable {
var value1: Int = _
var value2: Int = _
var result: Int = _
var op: (Int, Int) => Int = _
def setValue1(value1: Int) = {
this.value1 = value1
}
def setValue2(value2: Int) = {
this.value2 = value2
}
def setOp(op: (Int, Int) => Int) = {
this.op = op
}
def setResult(result : Int) = {
this.result = result
}
}
4.运行结果
Processor
processor 收到 Task, 处理 Task ...
处理器处理完毕, 计算的结果是: 7
Sender
Task 发送到 processor ...
sender 收到的结果是:7