Home > Java > javaTutorial > Implementing a simple calculator over UDP using Java Implement a simple calculator using UDP in Java

Implementing a simple calculator over UDP using Java Implement a simple calculator using UDP in Java

王林
Release: 2023-08-27 21:33:02
forward
1106 people have browsed it

使用Java通过UDP实现简单计算器

在Java中使用UDP实现一个简单的计算器

The Internet Protocol Suite contains all types of protocols that enable devices to communicate with each other over the Internet. UDP is one of the protocols of this suite, and its full form is User Datagram Protocol. Unlike TCP, it is unreliable and a connectionless protocol. It does not establish any type of connection with other devices before sending data.

In this article, we will develop a simple client-server calculator using UDP in Java. The client requests an operation, and the server calculates and sends the result to the client device.

Java Network

Let us first briefly understand some basic concepts about Java networking−

Inet address

An IP address is a 32-bit or 128-bit unsigned number that uniquely identifies a device on the Internet. It's easier to remember the name of an IP host than the numeric address. Therefore, we need to use the "InetAddress" class to encapsulate it. We use its built-in method "getLocalHost()" to get the IP address of the local host.

Datagram

They are small packets containing data that can be passed between two machines over the Internet. Java implements two classes to establish UDP connections -

DatagramSocket class is used to send and receive datagram packets. It also determines the destination of these packages. Its built-in methods 'send()' and 'receive()' are used to send and receive data packets respectively.

grammar

DatagramSocket nameOfObject = new DatagramSocket();   
Copy after login
The object of class

DatagramPacket stores the data to be sent.

grammar

DatagramPacket nameOfPacket = new DatagramPacket();   
Copy after login

Calculator program using UDP

Client program

How the code works

  • We first import the two most important packages named 'java.net' which is used to access all classes related to Java networking, and 'java.io' , for input and output streams. Use the 'java.util' package to use the 'Scanner' class.

  • Establish a UDP connection and then obtain the local host address.

  • Now, inside the try block, we will request user input through the 'send()' and 'receive()' methods of the 'DatagramSocket' class to request the operation and receive the result accordingly.

import java.io.*;
import java.net.*;
import java.util.*;
public class ClientCalc {
   public static void main(String args[]) throws IOException {
      Scanner inp = new Scanner(System.in);
      // making UDP connection
      DatagramSocket datagsokt = new DatagramSocket();   
      // fetching the localhost address
      InetAddress addr = InetAddress.getLocalHost();
      byte strm[] = null;
      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: ");
            String oprtr = inp.nextLine();
            // to convert the user choice to byte
            strm = new byte[256];
            strm = oprtr.getBytes();
            // creating datagram packet to send to server
            DatagramPacket packtsend = new DatagramPacket(strm, strm.length, addr, 6666);
            datagsokt.send(packtsend);
            // Type 0 for cut the connection
            if (oprtr.equals("0")) {
               break;
            }
            // to receive the result from server
            strm = new byte[256];
            DatagramPacket packtrec = new DatagramPacket(strm,   strm.length);
            datagsokt.receive(packtrec);
            // display the result 
            System.out.println("Your Result for the given operation = " + new String(strm, 0, strm.length));
         }
      }
      // to handle exception
      catch(Exception exp) {
         System.out.println(exp);
      } 
   }
}
Copy after login

Server-side program

How the code works

  • First, establish a connection with the client and define two objects of the DatagramPacket class to send and receive data packets using the "send()" and "receive()" methods of the "DatagramSocket" class.

  • Inside the try block, we receive the request from the client and then use switch case to perform the operation and send the result to the client device.

Example

import java.io.*;
import java.net.*;
class ServerCalc {
   public static void main(String[] args) throws IOException {
      // making connection to client
      DatagramSocket datagsokt = new DatagramSocket(6666);
      byte[] strm = null;
      DatagramPacket packtrec = null;
      DatagramPacket packtsend = null;
      try {
         while (true) {
            strm = new byte[256];
            // to receive the packet from client
            packtrec = new DatagramPacket(strm, strm.length);
            datagsokt.receive(packtrec);
            String oprtr = new String(strm, 0, strm.length);
            System.out.println("Client has requested for " + oprtr );
            int data1 = 15;
            int data2 = 5;
            int tot = 0;
            char opt = oprtr.charAt(0); 
            switch(opt) {
               case '1' : 
                  tot = data1 + data2;
               break;
               case '2' :
                  tot = data1 - data2;  
               break;
               case '3' :
                  tot = data1 * data2;
               break;
               case '4' :
                  tot = data1 / data2;  
               break;
               default :
               break; 
            }
            // Converting the string result to integer 
            String res = Integer.toString(tot);
            // converting the integer to bytes
            strm = res.getBytes();
            int port = packtrec.getPort(); 
            // getting port number
            // sending final result in the form of datagram packet
            packtsend = new DatagramPacket(strm, strm.length, InetAddress.getLocalHost(), port);
            datagsokt.send(packtsend);
         }
      }
      // to handle exception
      catch(Exception exp) {
         System.out.println(exp);
      } 
   }
}
Copy after login

To run both programs at the same time, open both cmds simultaneously on your local machine. On the first cmd interface, compile and run the server-side program, and then execute the client program on the other interface.

Client output

D:\Java Programs>java ClientCalc
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  
Copy after login

Server-side output

D:\Java Programs>java ServerCalc
Client has requested for 1  
Copy after login

When we enter 0, the connection will be terminated and the program will stop executing.

in conclusion

In this article, we learned about some basic concepts of Java networking. Additionally, we discussed server-side and client-side programs for a simple calculator using UDP. We discovered how to establish a connection between client and server devices using Java.

The above is the detailed content of Implementing a simple calculator over UDP using Java Implement a simple calculator using UDP in Java. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template