保持套接字服务器可以多次使用?

时间:2014-03-12 23:45:30

标签: java serversocket

在Client类中有一个while循环,我要求用户进行一些计算。当我尝试进行多个计算时出现问题。它坚持从Server类进行计算。

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

public class Client {

private static final int PORT = 1234;

public static void main(String[] arg) {
  try {

      Scanner userInputScanner = new Scanner(System.in);

      Calculator c = new Calculator(0,0,"+");
      CalculatorProtocol s = new CalculatorProtocol();
      String testString = null;
      String answer = null;

      Socket socketConnection = new Socket(InetAddress.getLocalHost(),PORT);
      ObjectOutputStream clientOutputStream = new
              ObjectOutputStream(socketConnection.getOutputStream());
           ObjectInputStream clientInputStream = new 
              ObjectInputStream(socketConnection.getInputStream());

      do{

         System.out.println("Give the 1st integer:");
         testString = userInputScanner.next();
         while (!s.isInteger(testString)) {
             System.out.println("Wrong input data." + "Give the 1st integer:");
             testString = userInputScanner.next();
         }
         c.setFirstNumber(Integer.parseInt(testString));            

         System.out.println("Give the 2nd integer:");
         testString = userInputScanner.next();

         while (!s.isInteger(testString)) {
             System.out.println("Wrong input data." + "Give the 2nd integer:");
             testString = userInputScanner.next();
         }                   
         c.setSecondNumber(Integer.parseInt(testString));
         userInputScanner.nextLine(); // Gia na mi ginei lathos

         System.out.println("Give the operator (+,-,*,/):");
         testString = userInputScanner.nextLine();
         while(!s.isOperator(testString)) {
            System.out.println("Wrong input data."                          
                    + "Give the operator(+,-,*,/):");
            testString = userInputScanner.next();
         }
        c.setOperation(testString);

        System.out.println("First integer:" +c.getFirstNumber());
        System.out.println("Second integer:" +c.getSecondNumber());
        System.out.println("Operator:"+c.getOperation());                   

      clientOutputStream.writeObject(c);

      c = (Calculator)clientInputStream.readObject();


      System.out.println("Result="+c.getResult());

      System.out.println("Want more?");          
      answer = userInputScanner.nextLine();
      }while(s.wantMore(answer));

      clientOutputStream.close();
      clientInputStream.close();



  }catch (Exception e) {System.out.println(e); }
        }
}

服务器类

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

public class Server {

  private static final int PORT = 1234;

  public static void main(String[] arg) {

  Calculator c = null;
  CalculatorProtocol s = new CalculatorProtocol();
  String answer = null;



      try {
              ServerSocket socketConnection = new ServerSocket(PORT);

              System.out.println("Server Waiting");


              while(true) {
                  Socket pipe = socketConnection.accept();
                  ObjectInputStream serverInputStream = new    
                                   ObjectInputStream(pipe.getInputStream());

                         ObjectOutputStream serverOutputStream =   new 
                                    ObjectOutputStream(pipe.getOutputStream());
                       c =    (Calculator)serverInputStream.readObject();
                     while (true) {


                        c.setResult(s.Calculate(c.getFirstNumber(), c.getSecondNumber()
                                , c.getOperation() ));
                        serverOutputStream.writeObject(c);

                     }



              }




          }  catch(Exception e) {System.out.println(e); 
  }


  }
}

协议类

public class CalculatorProtocol  {


private int a , b ;
private String d;




public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
        if (length == 1) {
            return false;
        }
        i = 1;
    }
    for (; i < length; i++) {
        char c = str.charAt(i);
        if (c <= '/' || c >= ':') {
            return false;
        }
    }
    return true;
}

public boolean isOperator(String op){
    if(!(op.equals("+") || op.equals("-") || op.equals("*") || op.equals("/")))
         return false;
    else
        d = op;
        return true;
}

public int Calculate(int n1 , int n2 , String o) {

    a = n1;
    b = n2;
    d = o;

    int result = 0;

    if (d.equals("+"))
        result = a + b;
    else if (d.equals("-"))
        result = a - b;
    else if (d.equals("*"))
        result = a * b;
    else 
        result = a/b;

    return result;
}

public boolean wantMore(String m){
    if (m.equals("Yes"))
        return true;
    else
        return false;
}



}



import java.io.*;
import java.util.*;

public class Calculator implements Serializable {

private int num1,num2,result;
private String calc;

计算器对象的计算器类。

Calculator (int a, int b, String p) {
  num1 = a;
  num2 = b;
  calc = p;
  result = 0;

}

public int getFirstNumber() {
  return num1 ;
}

public int getSecondNumber() {
    return num2 ;
 }

public void setFirstNumber(int num) {
  num1 = num;
}

public void setSecondNumber(int num) {
      num2 = num;
   }

public String getOperation() {
  return calc ;
}

public void setOperation(String op) {
  calc = op;
}

public void setResult(int d) {
   result = d;
}

public int getResult() {
   return result;
}
}

2 个答案:

答案 0 :(得分:0)

如果不筛选所有发布的代码,我会诊断您的问题。您似乎想要添加多个客户端来进行计算。它被困在这里。

while(true) {
    Socket pipe = socketConnection.accept();
    ObjectInputStream serverInputStream = new ObjectInputStream(pipe.getInputStream());

    ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream());
    c =    (Calculator)serverInputStream.readObject(); //this is only done once
    while (true) { // you need logic to break out of this loop.
        c.setResult(s.Calculate(c.getFirstNumber(), c.getSecondNumber(), c.getOperation() ));
        serverOutputStream.writeObject(c); //this is done multiple times
    }

假设您只想一次处理一个客户端,您想要做的是从该客户端进行计算,直到它不再想要发送它们为止。然后假设您将接收一个对象,然后写一个对象并冲洗并重复,您需要做的更改如下。

    ObjectInputStream serverInputStream = new ObjectInputStream(pipe.getInputStream());
    ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream());
    while (true) { 
        c =    (Calculator)serverInputStream.readObject();
        c.setResult(s.Calculate(c.getFirstNumber(), c.getSecondNumber(),c.getOperation() ));
        serverOutputStream.writeObject(c);
    }

你需要添加一些逻辑来打破基于客户端离开的循环,或者将永远循环。

答案 1 :(得分:0)

服务器在循环中一遍又一遍地写c,等待客户端输入。

在下次计算时,客户端未获得c的更新版本。要获取更新对象的最新副本,您需要调用serverOutputStream.reset()

ObjectStreams为已写入的每个对象添加一个引用。您需要调用reset,删除以前写入的对象的所有引用。允许您发送已编辑的副本。

主要关注的是如何从服务器发送循环中的对象。你会不断地在一个永恒的循环中快速连续发送它。