【发布时间】:2020-08-30 23:58:48
【问题描述】:
我需要使用 TCP 套接字做一个简单的 ADD 应用程序,但它不起作用。我做错了什么? 我已经尝试了很多方法,以至于我想我错过了一些东西,我不知道是什么。你能帮助我一些你的知识吗? :)
public class Server {
static int total;
static int st;
static int nd;
public static int sum(int x, int y){
return x + y;
}
public static void main(String[] args) {
try(ServerSocket appServer = new ServerSocket(631);
Socket appSocket = appServer.accept();
BufferedReader inStream = new BufferedReader(new InputStreamReader(appSocket.getInputStream()));
BufferedOutputStream outStream = new BufferedOutputStream(appSocket.getOutputStream())){
String line = inStream.readLine();
while(line!=null&&line.equals("")){
st = Integer.parseInt(line.split(" ")[0]);
nd = Integer.parseInt(line.split(" ")[1]);
total = sum(st,nd);
}
String out = String.valueOf(total);
outStream.write(out.getBytes());
} catch(IOException e){
System.out.println("Server failed.");
System.out.println(e.getMessage());
}
}
}
and those from client:
public static void main(String[] args) {
String numbers = "1 2";
try(Socket client = new Socket("localhost", 631);
BufferedReader bis = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream())){
System.out.println("Client connected. Waiting for ADD numbers");
bos.write(numbers.getBytes());
bos.flush();
String res = bis.readLine();
while((res = bis.readLine()) != null){
System.out.println("The result is " + res);
}
} catch (IOException ex) {
System.out.println("Connection Problem. " + ex.getMessage());
}
}
}
Why this doesn't run as expected ( The result is 3 )?
【问题讨论】:
标签: java tcp client-server bufferedreader