使用线程

时间:2016-01-24 11:14:34

标签: java multithreading client-server

我正在尝试编写一个客户端服务器程序来处理使用服务器(Server1)的多个客户端请求,而服务器又从另一个服务器(计算服务器)请求计算。

客户端要求a1b1 + a2b2 + ...形式的表达式,其中a1,b1等是2X2矩阵。然后,用户输入表达式,然后输入2X2矩阵的值。客户端将每个值与','连接,同时为每个矩阵添加';'并将结果字符串发送到服务器(Server1)。

服务器(Server1)在接收到该表达式时,将其分解为令牌(由“+”分隔)并将令牌(a1和b1的值)转发给另一个计算服务器。计算服务器(1)从Server1接收令牌,(2)提取2X2矩阵并执行它们的矩阵乘法,以及(3)将矩阵乘法的结果返回给Server1。然后,Server1计算计算服务器返回的值的总和,并将最终结果发送回客户端。

例如,如果用户输入类似'a1b1 + a2b2'(无空格)和值1,1,1,1(对于矩阵a1)等表达式,则客户端以Server 1的形式向Server1发送字符串'1,1,1,1; 2,2,2,2; +3,3,3,3; 4,4,4,4; +'。 Server1发送1,1,1,1; 2,2,2,2;到计算服务器。计算服务器计算{1,1,1,1}和{2,2,2,2}的矩阵乘法,并将结果{4,4,4,4}返回给Server1。 Server1再次发送3,3,3,3; 4,4,4,4;到计算服务器等。最后,Server1将表达式{28,28,28,28}的结果返回给客户端。

我的代码如下:

TCPClient.java

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

public class TCPClient{
public static void main(String [] args) throws Exception{
    Socket s = new Socket("127.0.0.1",5555);
    DataOutputStream out = new DataOutputStream(s.getOutputStream());

    System.out.print("Enter an expression of the form a1b1+a2b2... : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String exp = br.readLine();
    String exp2 = "";
    int terms = exp.length() - exp.replace("+", "").length() + 1;
    int i = 1;
    String input;
    do{
        System.out.print("\nEnter value for element 00 of a" + i + ": ");
        input = br.readLine();
        exp2 += input + ",";
        System.out.print("Enter value for element 01 of a" + i + ": ");
        input = br.readLine();
        exp2 += input + ",";
        System.out.print("Enter value for element 10 of a" + i + ": ");
        input = br.readLine();
        exp2 += input + ",";
        System.out.print("Enter value for element 11 of a" + i + ": ");
        input = br.readLine();
        exp2 += input + ";";

        System.out.print("\nEnter value for element 00 of b" + i + ": ");
        input = br.readLine();
        exp2 += input + ",";
        System.out.print("Enter value for element 01 of b" + i + ": ");
        input = br.readLine();
        exp2 += input + ",";
        System.out.print("Enter value for element 10 of b" + i + ": ");
        input = br.readLine();
        exp2 += input + ",";
        System.out.print("Enter value for element 11 of b" + i + ": ");
        input = br.readLine();
        exp2 += input + ";+";

        i++;
    }while(i <= terms);

    System.out.println("\nExpression sent to server = "+exp2);      
    out.writeUTF(exp2);

    DataInputStream in = new DataInputStream(s.getInputStream());
    String result = in.readUTF();
    System.out.println("\nResult of expression is "+ result);
    s.close();
}
}

TCPServer1.java

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

public class TCPServer1{
public static void main(String [] args) throws Exception{
    ServerSocket ss = new ServerSocket(5555);
    System.out.println("Server started...");

    while(true){
        Socket s = ss.accept();
        Connection c = new Connection(s);
    }
}
}

class Connection extends Thread{
Socket c;
DataInputStream in;
DataOutputStream out;
public Connection(Socket c) throws Exception{
    this.c = c;
    in = new DataInputStream(c.getInputStream());
    out = new DataOutputStream(c.getOutputStream());
    this.start();
}
public void run(){
    try{
        String data = new String();
        data = in.readUTF();
        System.out.println("Received from client: " + data);
        data = data.substring(0, data.length()-1);
        System.out.println("data: " + data);
        String[] tokens = data.split("\\+");
        System.out.println("tokens[0]: " + tokens[0]);
        int[][] finalsum = new int [2][2];

        Socket s = new Socket("127.0.0.1",6666);
        DataOutputStream out2 = new DataOutputStream(s.getOutputStream());

        int numtokens = tokens.length;
        int i = 0;
        while (i < numtokens) {
            System.out.println("Writing to CM: " + tokens[i]);
            out2.writeUTF(tokens[i]);
            DataInputStream in2 = new DataInputStream(s.getInputStream());
            String matmul = in2.readUTF();
            System.out.println("Received from Computation Machine: " + matmul);
            findSum(finalsum, matmul);
            System.out.println("Finalsum intermediate: " + finalsum[0][0] + " " + finalsum[0][1] + " " + finalsum[1][0] + " " + finalsum[1][1]);
            i++;
        }
        String finalres = String.valueOf(finalsum[0][0]) + "," +String.valueOf(finalsum[0][1]) + ",";
        finalres += String.valueOf(finalsum[1][0]) + "," + String.valueOf(finalsum[1][1]);
        System.out.print("finalres to be sent to client: " + finalres);
        out.writeUTF(finalres);
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        try{
            c.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

public static void findSum(int [][] finalsum, String matmul) {
    int [][] arr = new int [2][2];
    String[] tokens = matmul.split(",");

    arr[0][0] = Integer.parseInt(tokens[0]);
    arr[0][1] = Integer.parseInt(tokens[1]);
    arr[1][0] = Integer.parseInt(tokens[2]);
    arr[1][1] = Integer.parseInt(tokens[3]);

    for(int i = 0; i < 2; i++)
        for(int j = 0; j < 2; j++)
            finalsum[i][j] += arr[i][j];
}
}

ComputationServer.java

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

public class ComputationServer {
public static void main(String [] args) throws Exception{
    ServerSocket ss = new ServerSocket(6666);
    System.out.println("Computation Server started...");
    int count = 1;

    Socket s = ss.accept();
    DataInputStream in;
    DataOutputStream out;
    in = new DataInputStream(s.getInputStream());
    out = new DataOutputStream(s.getOutputStream());

    while(true){
        System.out.println("Entered CM " + (count++) + " times");
        String data = in.readUTF();
        System.out.println("Received from server: " + data);

        String[] tokens = data.split(";");
        System.out.println("tokens[0]: " + tokens[0]);
        System.out.println("tokens[1]: " + tokens[1]);

        String[] subtoken1 = tokens[0].split(",");
        String[] subtoken2 = tokens[1].split(",");
        int[][] first = new int [2][2];
        int[][] second = new int [2][2];

        first[0][0] = Integer.parseInt(subtoken1[0]);
        first[0][1] = Integer.parseInt(subtoken1[1]);
        first[1][0] = Integer.parseInt(subtoken1[2]);
        first[1][1] = Integer.parseInt(subtoken1[3]);

        second[0][0] = Integer.parseInt(subtoken2[0]);
        second[0][1] = Integer.parseInt(subtoken2[1]);
        second[1][0] = Integer.parseInt(subtoken2[2]);
        second[1][1] = Integer.parseInt(subtoken2[3]);

        int[][] res = new int [2][2];

        for(int i = 0; i < 2; i++)
            for(int j = 0; j < 2; j++)
                for(int k = 0; k < 2; k++)
                    res[i][j] += first[i][k] * second[k][j];

        String matmul = String.valueOf(res[0][0]) + "," +String.valueOf(res[0][1]) + ",";
        matmul += String.valueOf(res[1][0]) + "," + String.valueOf(res[1][1]);
        System.out.println("matmul: " + matmul);
        out.writeUTF(matmul);
        //out.flush();
    }
}
}

为了执行,我首先启动Computation服务器,然后启动Server1,然后启动客户端程序。

我遇到的问题是我的程序适用于第一个客户端,但如果我尝试为第二个客户端计算这个,则计算服务器不接受进一步的请求。

如果我按如下方式更改我的计算服务器,那么它不接受来自Server1的第二个令牌(对于第一个客户端)。

ComputationServer.java

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

public class ComputationServer {
public static void main(String [] args) throws Exception{
    ServerSocket ss = new ServerSocket(6666);
    System.out.println("Computation Server started...");
    int count = 1;

    while(true){
        System.out.println("Entered CM " + (count++) + " times");
        Socket s = ss.accept();
        DataInputStream in;
        DataOutputStream out;
        in = new DataInputStream(s.getInputStream());
        out = new DataOutputStream(s.getOutputStream());
        String data = in.readUTF();
        System.out.println("Received from server: " + data);
//rest of the code same as above

非常感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

我认为“它不起作用”意味着来自第二个客户端的调用永远不会到达您的ComputationServer。您的ComputationServer只接受一个连接,然后它不受限制地循环,再也不会进入accept方法。那么为什么你希望server1在收到第二个请求后能够打开一个新的连接呢?