使用 Java 实现 TCP 简单计算器
互联网协议套件包含各种协议,这些协议使设备能够通过互联网进行通信。TCP 是此套件中最常见的协议。它是一种面向连接的协议,这意味着它在两个设备之间维持已建立的连接,直到通信结束。这就是在网络冲浪、发送电子邮件和传输文件时使用它的原因。
在本文中,我们将使用 Java 中的 TCP 开发一个简单的客户端-服务器端计算器。客户端将请求操作,服务器将在计算后将结果发送到客户端设备。
Java 网络
让我们首先简要了解一些关于 Java 网络的基本概念。
InetAddress
IP 地址是一个 32 位或 128 位无符号数字,用于唯一标识互联网上的设备。记住 IP 主机的名称比记住数字地址更容易。因此,我们需要使用“InetAddress”类将其封装起来。我们使用其内置方法“getLcalHost()”来检索 LocalHost 的 IP 地址。
Socket
它是 Java 网络概念的基础,它允许设备同时为多个客户端提供服务。有两种 TCP 套接字类。一个是“ServerSocket”类,用于接收并向客户端设备发送结果的服务器;另一个是“Socket”类,用于客户端请求信息。
I/O 流
流是在 Java 网络中执行输入和输出操作时使用的抽象。通过使用“getInputStream()”和“getOutputStream()”,我们可以访问与“Socket”类关联的输入和输出流。
使用 TCP 的计算器程序
客户端程序
代码工作原理
我们首先导入两个最重要的包,名为“java.net”以访问所有关于 Java 网络的类,以及“java.io”用于输入和输出流。“java.util”包用于使用“Scanner”类。
获取 LocalHost 地址,然后将端口号和地址存储在“Socket”类的对象中。
定义两个名为“inpStrm”的对象来接收数据,以及“outpStrm”的对象以流的形式发送数据。
现在,在 try 块内部,我们将要求用户输入以请求操作并相应地接收结果。
示例
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientCal {
public static void main(String[] args) throws IOException {
// fetching address of localhost
InetAddress addr = InetAddress.getLocalHost();
Scanner inp = new Scanner(System.in);
// establishing socket connection
Socket sock = new Socket(addr, 6666);
// to send and receive data through streams
DataInputStream inpStrm = new DataInputStream(sock.getInputStream());
DataOutputStream outpStrm = new DataOutputStream(sock.getOutputStream());
try {
while (true) {
System.out.println("Type 1 for Addition");
System.out.println("Type 2 for Subtraction");
System.out.println("Type 3 for Multiplication");
System.out.println("Type 4 for Division");
System.out.println("Enter your choice: ");
int oprtr = inp.nextInt();
// Type 0 for cut the connection
if (oprtr == 0) {
break;
}
// sending the operator for operation
outpStrm.writeInt(oprtr);
// reading result from server
String res = inpStrm.readUTF();
System.out.println("Your Result for the given operation = " + res);
}
}
// to handle exception
catch(Exception exp) {
System.out.println(exp);
}
}
}
服务器端程序
代码工作原理
首先,与客户端建立连接。
然后从客户端读取请求。
在 try 块内部,使用 switch case 执行操作并将结果发送到客户端设备。
catch 块用于处理运行时期间的任何类型的异常。
示例
import java.io.*;
import java.net.*;
import java.util.*;
public class ServeCalc {
public static void main(String args[]) throws IOException {
// establishing the socket connection
ServerSocket Serve = new ServerSocket(6666);
Socket sock = Serve.accept();
// to send and receive data through streams
DataInputStream inpStrm = new DataInputStream(sock.getInputStream());
DataOutputStream outpStrm = new DataOutputStream(sock.getOutputStream());
try {
while (true) {
// reading input from client
int oprtr = inpStrm.readInt();
System.out.println("Client has requested for " + oprtr + " operation");
int res = 0;
int data1 = 15;
int data2 = 5;
switch(oprtr) {
case 1 :
res = data1 + data2;
outpStrm.writeUTF(Integer.toString(res));
break;
case 2 :
res = data1 - data2;
outpStrm.writeUTF(Integer.toString(res));
break;
case 3 :
res = data1 * data2;
outpStrm.writeUTF(Integer.toString(res));
break;
case 4 :
res = data1 / data2;
outpStrm.writeUTF(Integer.toString(res));
break;
default :
outpStrm.writeUTF(" You have given invalid choice! ");
break;
}
System.out.println("Result sent to the client...");
}
}
// to handle exception
catch(Exception exp) {
System.out.println(exp);
}
}
}
要运行这两个程序,请在本地计算机上同时打开两个 cmd。在第一个 cmd 界面上,编译并运行服务器端程序,然后在另一个界面上执行客户端程序。
服务器端输出
D:\Java Programs>javac ServeCalc.java D:\Java Programs>java ServeCalc Client has requested for 1 operation Result sent to the client... Client has requested for 2 operation Result sent to the client... Client has requested for 3 operation Result sent to the client... Client has requested for 4 operation Result sent to the client... java.net.SocketException: Connection reset
客户端输出
D:\Java Programs>javac ClientCal.java D:\Java Programs>java ClientCal Type 1 for Addition Type 2 for Subtraction Type 3 for Multiplication Type 4 for Division Enter your choice: 1 Your Result for the given operation = 20 Type 1 for Addition Type 2 for Subtraction Type 3 for Multiplication Type 4 for Division Enter your choice: 2 Your Result for the given operation = 10 Enter your choice: 0
当我们输入 0 时,连接将被终止,程序将停止执行。
结论
在本文中,我们学习了 Java 网络的一些基本概念。还讨论了使用传输控制协议的简单计算器的服务器端和客户端程序。我们了解了如何在 Java 中在客户端和服务器设备之间建立连接。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP