09 April 2016

NumberClient NumberServer

 MVC: Model   View   Controller

Design Patterns - MVC

package network.sample;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

import network.sample.model.NumberModel;

public class NumberClient {
 public static void main(String args[]) {
  try {
   Socket myClient = new Socket("localhost", 9768);
   
   NumberModel number = new NumberModel();
   
   ObjectOutputStream oos = new ObjectOutputStream(myClient.getOutputStream());
   ObjectInputStream ois = new ObjectInputStream(myClient.getInputStream());
   
   Scanner scanner = new Scanner(System.in);
   
   System.out.println("Nhap so a: ");
   number.setA(scanner.nextInt());
   
   System.out.println("Nhap so b: ");
   number.setB(scanner.nextInt());
   
   oos.writeObject(number);
   scanner.close();
   
   int sum = (int) ois.readObject();
   System.out.println("Result: " + sum);
   
   myClient.close();
   
  } catch (IOException | ClassNotFoundException e) {
   e.printStackTrace();
  }
  
 }
}

package network.sample;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import network.sample.controller.NumberController;
import network.sample.model.NumberModel;

public class NumberServer {
 public static void main(String args[]) {
  try {
   ServerSocket myServer = new ServerSocket(9768);
   
   Socket serverSocket = myServer.accept();
   
   ObjectOutputStream oos = new ObjectOutputStream(serverSocket.getOutputStream());
   ObjectInputStream ois = new ObjectInputStream(serverSocket.getInputStream());
   
   while(true){
    NumberModel number = (NumberModel) ois.readObject();
    NumberController controller = new NumberController();
    
    int sum = controller.calculate(number);
    oos.writeObject(sum);
    break;
   }
   myServer.close();
  } catch (IOException | ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}
package network.sample.controller;

import network.sample.model.NumberModel;

public class NumberController {
 public int calculate(NumberModel num){
  int sum = num.getA() + num.getB();
  
  return sum;
 }
}
package network.sample.model;

import java.io.Serializable;

public class NumberModel implements Serializable{
 private int a;
 private int b;
 public int getA() {
  return a;
 }
 public void setA(int a) {
  this.a = a;
 }
 public int getB() {
  return b;
 }
 public void setB(int b) {
  this.b = b;
 }
 
 
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang