我是新来的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();
}
}