我是 Java 计算机网络的新手,一开始并不擅长编程,但是,我能够构建这个应该只接受一行的服务器和客户端。一个函数(加、减、除)和两个整数,然后计算并打印答案。我可以将两者连接起来,但是当我在其中键入行时,它什么也不做。任何见解将不胜感激。谢谢!
服务器
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.lang.Math;
public class MathServer
{
public static void main(String[] args) throws IOException
{
ServerSocket yourSock = new ServerSocket(50000);
System.out.println("Please Wait....");
while(true)
{
Socket clientSock = yourSock.accept();
System.out.println("Connected!");
process(clientSock);
}
}
static void process(Socket sock) throws IOException
{
InputStream in = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
OutputStream out = sock.getOutputStream();
PrintWriter pw = new PrintWriter(out,true);
//Talk to the client
String input = br.readLine();
while(input != null && !input.equals("disconnect"))
{
Scanner sc = new Scanner(System.in);
String func = sc.nextLine();
double num1 = sc.nextInt();
double num2 = sc.nextInt();
double answer;
switch (func)
{
case "add": answer = num1 + num2;
System.out.println(answer);
break;
case "sub": answer = num1 - num2;
pw.println(answer);
break;
case "multiply": answer = num1 * num2;
pw.println(answer);
break;
case "power": answer = Math.pow(num1, num2);
pw.println(answer);
break;
case "divide": answer = num1 / num2;
pw.println(answer);
break;
case "remainder": answer = num1 % num2;
pw.println(answer);
break;
case "square": answer = Math.sqrt(num1) ;
pw.println(answer);
break;
case "cube": answer= Math.cbrt(num1);
pw.println(answer);
break;
}
sock.close();
}
}
}
客户
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client
{
public static void main(String[] args) throws Exception
{
Socket Sock = new Socket("localhost", 50000);
BufferedReader br = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
PrintWriter pw = new PrintWriter(Sock.getOutputStream(), true);
Scanner sc = new Scanner(System.in);
String input;
while(true)
{
//System.out.println("Please enter your function and numbers:");
input = sc.nextLine();
pw.println(input);
if(input.equals("disconnect"))
{
System.out.println("You have been disconnected");
break;
}
System.out.println(br.readLine());
}
Sock.close();
}
}