myserver.java

来自「简单cs编程,由于客户端请求服务器计算,无gui组件」· Java 代码 · 共 58 行

JAVA
58
字号
import java.io.*;
import java.net.*; 
public class MyServer { 
//定义calculator-----------
static int a=0,b=0,c=0;
     public static int result(int l,int m,int n)
    {
          switch(m)
          {
              case 1:
                  return (l+n);
              case 2:
                  return (l-n);
              case 3:
                  return (l*n);
              case 4:
                  return (l/n);
              default:
                  System.out.print("error\n");
                  return 0;          
          }
    }
public static void main(String[] args) throws IOException{ 
System.out.print("The server is waiting^_^\n"); 
ServerSocket server=new ServerSocket(20000); 
Socket client=server.accept();

System.out.println("Receive the request from "+client.getInetAddress()+" and the port is "
			+client.getPort());
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream())); 
PrintWriter out=new PrintWriter(client.getOutputStream()); 

//-----------------------------------
while(true){
String str=in.readLine(); 
System.out.println(str);
if((a!=0&&b!=0&&c!=0)||str.equals("end"))
   break;
if(a==0){
	a=Integer.parseInt(str);
		out.println("has receive...."+
	"And select the option to calculate:1 to add,"+
	"2 to sub,3 to multiple,4 to divide"); 
	out.flush();}
else if(b==0)
	b=Integer.parseInt(str);
else if(c==0){
	c=Integer.parseInt(str);
out.println("The result is: "+result(a,b,c)); 
out.flush();}
out.println("has receive....");	out.flush();
}
out.println("The illeagal operation,the server can only do as a caculator.Put end to quit");
out.flush();
client.close(); 
}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?