分布式计算第二次作业

题目

实现一个支持并发服务的 网络 运算 服务器程序。该服务器能够同时接收来自于多个客户端的运算请求,然后根据运算类型和请求参数完成实际的运算,最后把运算结果返回给客户端。

客户端


import java.io.IOException;
import java.net.*;


public class Client  {

    private DatagramSocket datagramSocket;
    private InetAddress address ;
    private int port;

    public Client(){
        this(18888,"127.0.0.1");
    }
    public Client(int port, String netAddress){
        try {
            this.port=port;
            datagramSocket = new DatagramSocket(); //发送端口可以不指定
            address=InetAddress.getByName(netAddress);

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }


    public void send(String requestParam) {
        try {
            DatagramPacket datagramPacket = new DatagramPacket(requestParam.getBytes(), requestParam.length(),address,port);
            datagramSocket.send(datagramPacket);

            String[] str =requestParam.split("\n");
            System.out.print("send: ");
            for(String s:str){
                System.out.print(s+" ");
            }
            System.out.println();

            byte[] receiveBuff = new byte[1024];
            DatagramPacket receivePaket = new DatagramPacket(receiveBuff,receiveBuff.length);
            datagramSocket.receive(receivePaket);
            String receiveParam = new String(receivePaket.getData(),0,receivePaket.getLength());
            System.err.println("receive :"+receiveParam);
            System.out.println();

        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Client client = new Client();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i < 5; ++i) {
                    for (int j = 3; j < 5; ++j) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("x\n");
                        sb.append(i);
                        sb.append("\n");
                        sb.append(j);
                        sb.append("\n");
                        client.send(sb.toString());
                    }
                }
            }
        };

        for(int i=0;i<3;++i){
            new Thread(runnable).start();
        }


    }
}

服务端


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;



public class Server {
    private static final int PORT=18888;
    private static final int MAX_LENGTH=1024;

    private DatagramSocket datagramSocket;

    /**
     * 记录响应次数,线程安全用原子变量保证
     */
    private AtomicInteger modCount;

    private LinkedBlockingQueue<DatagramPacket> receiveQueue;
    private LinkedBlockingQueue<DatagramPacket> responseQueue;

    public Server(){
        try {
            datagramSocket = new DatagramSocket(PORT);
            receiveQueue =  new LinkedBlockingQueue<DatagramPacket>();
            responseQueue =  new LinkedBlockingQueue<DatagramPacket>();
            modCount = new AtomicInteger(0);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收线程,监听端口,收到数据包后直接放到接收队列
     */
    private void startReceive(){
        System.out.println("接收开启");
        //三个接收线程
        for(int i=0;i<3;++i){
            new Thread(()->{
                while(true){
                    //阻塞接收, 收到后就放入队列
                    byte[] buffer =new byte[MAX_LENGTH];
                    DatagramPacket receivePacket = new DatagramPacket(buffer,buffer.length);
                    try {
                        datagramSocket.receive(receivePacket);
                        receiveQueue.put(receivePacket);
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            },"receiveThread").start();
        }
    }

    /**
     * 处理线程,从接收队列取数据包,计算后封装新的包放入发送队列
     */
    private void startProcess(){
        System.out.println("处理开启");
        //开3个处理线程
        for(int i=0; i<3 ;++i){
            new Thread(()->{
                while(true){
                    DatagramPacket receivePacket=null;
                    try {
                        //阻塞式取数据
                        receivePacket = receiveQueue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String parameter  = new String(receivePacket.getData(),0,receivePacket.getLength());
                    String[] opers = parameter.split("\n");
                    double num1 = Double.parseDouble(opers[1]);
                    double num2 = Double.parseDouble(opers[2]);
                    //System.out.println(num1 +" "+opers[0]+" "+num2);
                    double res =0;
                    switch(opers[0]){
                        case "+" :
                            res = num1+num2;
                            break;
                        case "-":
                            res=num1-num2;
                            break;
                        case "x":
                            res=num1*num2;
                            break;
                        case "/":
                            res=num1/num2;
                            break;
                    }

                    //在原来的数据包上修改一下,省得再new一个
                    receivePacket.setData((res+"").getBytes());
                    try {
                        //放入相应队列
                        responseQueue.put(receivePacket);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
    }

    /**
     * 从发送队列取数据包,发出去
     */
    private void startResponse(){
        System.out.println("响应开启");
        //开三个发送线程
        for(int i=0;i<3;++i){
            new Thread(()->{
                while(true){
                    try {
                        DatagramPacket responsePacket = responseQueue.take();
                        datagramSocket.send(responsePacket);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    System.out.println("响应: "+ modCount.addAndGet(1));
                    //addModCount(); //modCount+1
                }
            },"responseThread").start();
        }
    }



    /**
     * 不知道在哪里关socket了,,就放这里吧 垃圾回收的时候关233333
     */
    protected void finalize(){
        if(datagramSocket!=null){
            datagramSocket.close();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();

        server.startResponse();
        server.startProcess();
        server.startReceive();

    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值