Trending February 2024 # C# Queue With Examples: What Is C# Queue And How To Use? # Suggested March 2024 # Top 9 Popular

You are reading the article C# Queue With Examples: What Is C# Queue And How To Use? updated in February 2024 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 C# Queue With Examples: What Is C# Queue And How To Use?

What is Queue in C#?

The Queue is a special case collection which represents a first in first out concept. Imagine a queue of people waiting for the bus. Normally, the first person who enters the queue will be the first person to enter the bus. Similarly, the last person to enter the queue will be the last person to enter into the bus. Elements are added to the queue, one on the top of each other.

The process of adding an element to the queue is the enqueuer operation. To remove an element from a queue, you can use the dequeuer operation. The operation in Queues C# is similar to stack we saw previously.

Let’s look at how to use Queue in C# and the operations available for the Queue collection in C# in more details.

Declaration of the Queue

The declaration of a Queue is provided below. A Queue is created with the help of the Queue Data type. The “new” keyword is used to create an object of a Queue. The object is then assigned to the variable qt.

Queue qt = new Queue() Adding elements to the Queue

The enqueue method is used to add an element onto the queue. The general syntax of the statement is given below.

Queue.enqueue(element) Removing elements from the queue

The dequeue method is used to remove an element from the queue. The dequeue operation will return the first element of the queue. The general syntax of the statement is given below

Queue.dequeue() Count

This property is used to get the number of items in the queue. Below is the general syntax of this statement.

Queue.Count Contains

This method is used to see if an element is present in the Queue. Below is the general syntax of this statement. The statement will return true if the element exists, else it will return the value false.

Queue.Contains(element)

Now, let’s see this working at a code level. All of the below-mentioned code will be written to our Console application.

The code will be written to our chúng tôi file. In the below program, we will write the code to see how we can use the above-mentioned methods.

Example

In this Queue in C# example, we will see how a queue gets created. Next, we will see how to display the elements of the queue, and use the Count and Contain methods.

C# Queue example

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { static void Main(string[] args) { Queue qt = new Queue(); qt.Enqueue(1); qt.Enqueue(2); qt.Enqueue(3); foreach (Object obj in qt) { Console.WriteLine(obj); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("The number of elements in the Queue " + qt.Count); Console.WriteLine("Does the Queue contain " + qt.Contains(3)); Console.ReadKey(); } } } Code Explanation

The first step is used to declare the Queue. Here we are declaring qt as a variable to hold the elements of our Queue.

Next, we add 3 elements to our Queue. Each element is added via the “enqueue” method.

Now one thing that needs to be noted about Queues is that the elements cannot be accessed via the index position like the array list. We need to use a different approach to display the elements of the Queue. So here’s how we go about displaying the elements of a queue.

We first declare a temporary variable called obj. This will be used to hold each element of the Queue.

We then use the foreach statement to go through each element of the Queue.

For each Queue element, the value is assigned to the obj variable.

We then use the Console.Writeline command to display the value to the console.

We are using the “Count” property to get the number of items in the Queue. This property will return a number. We then display this value to the console.

We then use the “Contains” method to see if the value of 3 is present in our Queue. This will return either a true or false value. We then display this return value to the console.

If the above code is entered properly and the program is run the following output will be displayed.

Output

Queue C# example

From the output, we can clearly see that the elements of the Queue are displayed. Note that, unlike “stack” in “queue” the first element pushed on to the queue is displayed first. The count of queue elements is also shown in the output. Also, the value of True is displayed to say that the value of 3 is defined on the queue.

C# Queue Dequeue

Now let’s look at the remove functionality. We will see the code required to remove the last element from the queue.

C# Queue Dequeue example

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { static void Main(string[] args) { Queue qt = new Queue(); qt.Enqueue(1); qt.Enqueue(2); qt.Enqueue(3); qt.Dequeue(); foreach (Object obj in qt) { Console.WriteLine(obj); } Console.ReadKey(); } } } Code Explanation

Here we just issue the “dequeue” method, which is used to remove an element from the queue. This method will remove the first element of the queue.

If the above code is entered properly and the program is run the following output will be displayed.

Output:

C# Queue Dequeue example

From the output, we can see that the first element which was added to the queue, which was the element 1, was removed from the queue.

Summary

A Queue is based on the first in first out concept. The operation of adding an element to the queue is called the enqueue operation. The operation of removing an element to the queue is called the dequeue operation.

You're reading C# Queue With Examples: What Is C# Queue And How To Use?

How Queue Works In Rust With Examples?

Definition on Rust Queue

Rust queue is a data structure that is used to store the elements, queue in Rust works in an FIO manner that means first in first out. This standard queue is available inside the rust collection library, and the queue is a linear data structure. Queue provides us with several operations that can be performed on it to made manipulation on it. We can add any number of elements inside it, all the implementation is based on the vector data structure in Rust. In rust, we have multiple varieties of a queue which can be used per the chúng tôi next section will cover the queue data structure in rust in detail for better understanding and its implementation while programming for better usage.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

A linear data structure is used to store and manipulate data elements. Here is a detailed syntax for implementing it in programming.

In the above syntax, we create a queue using the ‘Queue’ keyword as the variable type. We can specify the size of the queue and give it a custom name. This is a beginner-friendly syntax example for better understanding. We shall examine its internal operations in more detail in the section that follows.

e.g. :

In this way, we can create it.

How Queue works in Rust?

As we know, the queue is a linear data structure used to store elements. It is accessible as a collection in the standard library of the Rust computer language. But queue works the same way as in another programming language. In Rust, the queue follows the principle of FIFO (first in, first out). As a result, the queue will take out the first item that was put in, followed by the subsequent items in the order of their addition. For instance, we can take the example of a ticketing system, the person who comes first will get the ticket first, and out from the queue, it works in the same way.

Also, we have one more example, which is email queue processing, while drafting an email to multiple persons, it will follow the first email id mentioned, and so on. In this section, we will discuss the various types and methods available in rust, Let’s get started for more information, see below;

We have several types of a queue available in rust which is mentioned below;

Now let’s explore the different operations that we can perform on the queue in Rust, allowing us to manipulate it effectively. We have below mentioned different methods available in Rust for queue see below;

1) peek: The peek method allows us to retrieve the next element in the queue without removing it.

2) add: In Rust, we use the add method to add new element to the queue object. In Rust, we can also refer to this method as push or enqueue.

3) remove: This method removes elements from the queue. But as we already know, that queue works in a FIFO manner, so it always removes the oldest element from the queue. In Rust, we can also refer to this method as pop or dequeue.

Now we will see the following steps to use the queue inside the program in rust see below;

1) To use a queue inside our program, we must first include its dependency inside it. for this, we can add the below-mentioned dependency inside our chúng tôi file in rust, see below;

queues = "1.0.2"

2) After using this, we have to include or import this dependency in our file to use it, mentioned below the line of code inside the file. This is the official documentation of rust see below;

extern crate queues; use queues::*;

3) After this, you can create the queue object and assign it value inside your project. To create the queue object, follow the below line of code:

Example

1) In this example, we are trying to add the element inside the queue by using the add() method in the queue. Also, remember one point this example will run in a fully configured environment only. It will not go running by using any rust online compiler because we added dependency inside it. So first try to set up the configuration, then run it.

Code:

#[macro_use] extern crate queues; use queues::*; fn main() { println!("Demo pragrma to show queue in rust !!"); demoqueue.add(200); demoqueue.add(300); demoqueue.add(400); demoqueue.add(500); demoqueue.add(600); println!(" value inside the queue is {}", demoqueue ); }

Output:

Conclusion

We can store the elements inside by using a queue in rust. Programmers use this data structure to store and manipulate data using the various operations discussed in the tutorial. To utilize these functionalities in programming, programmers need to add the external library to the dependency file. Without doing so, the program will not compile or function properly.

Recommended Articles

We hope that this EDUCBA information on “Rust Queue” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Bucket Sort Algorithm (Java, Python, C/C++ Code Examples)

What is Bucket Sort?

Bucket sort, often called bin sort, is a comparison sort method that accepts an unsorted array as an input and produces a sorted array as a result. This method works by distributing the elements into several buckets and sorting each of those buckets individually by any sorting algorithm such as insertion sort. Then all the buckets are merged together to form a sorted array.

Bucket sort is commonly used when the elements are-

Floating-point values

Uniformly distributed over a range

Bucket sort’s time complexity depends on the number of buckets used and the uniformity of the input distribution. While different sorting algorithms such as shell sort, merge sort, heapsort, and quicksort can achieve the best-case time complexity of O(n*logn), the bucket sorting algorithm can achieve the same in linear time complexity or O(n).

Bucket sort follows the scatter-gather approach. Applying this approach, elements are scattered into the corresponding buckets, sorted in the buckets, and gathered to form a sorted array as the final step. This scatter-gather approach is discussed in the following section

Scatter-Gather-Approach

Large-scale, complex problems can occasionally be challenging to solve. The scatter-gather approach attempts to solve such problems by dividing the entire data set into clusters. Then each cluster is addressed separately and brought everything back together to get the final answer.

This is how the bucket sorting algorithm implements the scatter-gather method:

How Bucket Sort Works

The basic working principle of bucket sort is as follows:

A set of empty buckets is created. Based on different policies, the number of buckets can differ.

From the input array, put each element into its corresponding bucket.

Sort those buckets individually.

Concatenate the sorted buckets to create a single output array.

The in-detailed work steps are provided in the following sections.

Pseudo Code Start Create N empty buckets For each array element: Calculate bucket index Put that element into the corresponding bucket For each bucket: Sort elements within each bucket Merge all the elements from each bucket Output the sorted array End Method 1: Bucket Sort Algorithm for Floating-Point Numbers

The bucket sorting algorithm for floating point numbers within the range from 0.0 to 1.0:

Step 1) Create ten(10) empty buckets such that the first bucket will contain numbers within the range [0.0, 0.1). Then the second bucket will contain within [0.1, 0.2), and so on.

Step 2) For each array element:

bucket index= no_of_buckets *array_element

b. Insert the element into the bucket[bucket_index]

Step 3) Sort each bucket individually using insertion sort.

Step 4) Concatenate all buckets into a single array.

Let’s see a bucket sort example. For this example, we will sort the following array using the bucket sort algorithm-

Step 1) First, we will create 10 empty buckets. The first bucket will contain the numbers between [0.0, 0.1). Then the second bucket will contain the numbers between [0.1, 0.2) and so on.

Step 2) For each array element, we will calculate the bucket index and place the element into that bucket.

              bucket_index= no_of_buckets*array_element

Hence, the element 0.78 will be stored on the bucket[floor(7.8)] or bucket[7].

                   = 1.7

The array element 0.17 will be stored on bucket[floor(1.7)] or bucket[1].

   0.39 will be stored on bucket[floor(3.9)] or bucket[3].

After iterating over all array elements, the buckets will be the following:

Step 3) Then, each bucket will be sorted using insertion sort. After the sorting operation, the output would be:

Step 4) In the final step, the buckets will be concatenated into a single array. That array will be the sorted outcome of the input.

Each bucket will be concatenated to the output array. For example-the concatenation of the second bucket elements:

The concatenation of the last bucket elements will be the following:

After concatenation, the resulting array will be the desired sorted array.

Bucket Sort Program in C/C++

Input:

#define BUCKET_SIZE 10 using namespace std; void bucketSort(float input[], int array_size) { for (int i = 0; i < array_size; i++) { int index = BUCKET_SIZE*input[i]; bucket[index].push_back(input[i]); } for (int i = 0; i < BUCKET_SIZE; i++) sort(bucket[i].begin(), bucket[i].end()); int out_index = 0; for (int i = 0; i < BUCKET_SIZE; i++) for (int j = 0; j < bucket[i].size(); j++) input[out_index++] = bucket[i][j]; } int main() { float input[]={0.78,0.17,0.39,0.26,0.72,0.94,0.21,0.12,0.23,0.69}; int array_size = sizeof(input)/sizeof(input[0]); bucketSort(input, array_size); cout <<"Sorted Output: n"; for (int i = 0; i< array_size; i++) cout<<input[i]<<" "; return 0; }

Output:

Sorted Output: 0.12 0.17 0.21 0.23 0.26 0.39 0.69 0.72 0.78 0.94 Bucket Sort Program in Python

Input:

# Bucket Sort Program in Python # For not having integer parts def bucketSort(input): output = [] bucket_size = 10 for bucket in range(bucket_size): output.append([]) for element in input: index = int(bucket_size * element) output[index].append(element) for bucket in range(bucket_size): output[bucket] = sorted(output[bucket]) out_index = 0 for bucket in range(bucket_size): for element in range(len(output[bucket])): input[out_index] = output[bucket][element] out_index += 1 return input input = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.69] print("Sorted Output:") print(bucketSort(input))

Output:

Sorted Output: [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.69, 0.72, 0.78, 0.94] Bucket Sort in Java

Input:

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BucketSort { private static final int BUCKET_SIZE = 10; public static void bucketSort(float[] input, int arraySize) { List < [] bucket = new ArrayList[BUCKET_SIZE]; for (int i = 0; i < arraySize; i++) { int index = (int)(BUCKET_SIZE * input[i]); if (bucket[index] == null) { (); } bucket[index].add(input[i]); } for (int i = 0; i < BUCKET_SIZE; i++) { if (bucket[i] != null) { Collections.sort(bucket[i]); } } int outIndex = 0; for (int i = 0; i < BUCKET_SIZE; i++) { if (bucket[i] != null) { for (float value: bucket[i]) { input[outIndex++] = value; } } } } public static void main(String[] args) { float[] input = {0.78f,0.17f,0.39f,0.26f,0.72f,0.94f,0.21f,0.12f,0.23f,0.69f}; int arraySize = input.length; bucketSort(input, arraySize); System.out.println("Sorted Output:"); for (int i = 0; i < arraySize; i++) { System.out.print(input[i]+" "); } } }

Output:

Sorted Output: 0.12 0.17 0.21 0.23 0.26 0.39 0.69 0.72 0.78 0.94

Method 2: Bucket Sort Algorithm for Integer Elements

The bucket sort algorithm for the input that contains numbers beyond the range [0.0, 1.0] is a little bit different than the previous algorithm. The steps required for this case are as follows-

Step 1) Find the maximum and minimum elements.

Step 2) Select the number of buckets, n, and initialize those buckets as empty.

               span = (maximum - minimum)/n

Step 4) For each array element:

               bucket_index = (element - minimum)/span

2.Insert the element into bucket[bucket_index]

Step 5) Sort each bucket using insertion sort.

Step 6) Concatenate all the buckets into a single array.

Let’s see an example of this bucket sort algorithm. For this example, we will sort the following array using the bucket sort algorithm-

Step 1) In the first step, the maximum and minimum elements of the given array need to be found. For this example, the maximum is 24 and the minimum is 1.

Step 2) Now, we have to select a number of empty buckets, n. In this example, we will take 5 buckets. Then we will initialize them as empty.

               span = (maximum-minimum)/n = (24-1)/5 = 4;

Hence, the first bucket will contain the numbers within the range [0, 5). The second bucket will contain the numbers within [5, 10) and so on.

               bucket_index = (element - minimum)/span

Bucket Index Calculation:

                   =2

Thus, element 11 will be stored in bucket[2].

                   =2

Note: As 9 is a boundary element for the bucket[1], it needs to be appended in bucket[1] instead of appending in the same bucket of the previous element.

After performing the operations for each element, the buckets will be as follows:

Step 5) Now, each bucket will be sorted using insertion sort. The buckets after sorting-

Step 6) In the final step, the buckets will be concatenated into a single array. That array will be the sorted outcome of the input.

Bucket Sort Program in C/C++

Input:

using namespace std; { double max_value = * max_element(input.begin(), input.end()); double min_value = * min_element(input.begin(), input.end()); double span = (max_value – min_value) / No_Of_Buckets; output; for (int i = 0; i < No_Of_Buckets; i++) ()); for (int i = 0; i < input.size(); i++) { double difference = (input[i] – min_value) / span – int((input[i] – min_value) / span); if (difference == 0 && input[i] != min_value) output[int((input[i] – min_value) / span) – 1] .push_back(input[i]); else output[int((input[i] – min_value) / span)].push_back( input[i]); } for (int i = 0; i < output.size(); i++) { if (!output[i].empty()) sort(output[i].begin(), output[i].end()); } int index = 0; { if (!bucket.empty()) { for (double i: bucket) { input[index] = i; index++; } } } } int main() { input ={11,9,21,8,17,19,13,1,24,12 }; int No_Of_Buckets = 5; bucketSort(input, No_Of_Buckets); cout<< “Sorted Output:”; for (int i; i < input.size(); i++) cout <<input[i]<<” “; return 0; }

Output:

Sorted Output:1 8 9 11 12 13 17 19 21 24 Bucket Sort Program in Python

Input:

def bucketSort(input, No_Of_Buckets): max_element = max(input) min_element = min(input) span = (max_element - min_element) / No_Of_Buckets output = [] for bucket in range(No_Of_Buckets): output.append([]) for element in range(len(input)): diff = (input[element] - min_element) / span - int( (input[element] - min_element) / span ) if diff == 0 and input[element] != min_element: output[int((input[element] - min_element) / span) - 1].append( input[element] ) else: output[int((input[element] - min_element) / span)].append(input[element]) for bucket in range(len(output)): if len(output[bucket]) != 0: output[bucket].sort() index = 0 for bucket in output: if bucket: for element in bucket: input[index] = element index = index + 1 input = [11, 9, 21, 8, 17, 19, 13, 1, 24, 12] No_Of_Buckets = 5 bucketSort(input, No_Of_Buckets) print("Sorted Output:n", input)

Output:

Sorted Output: [1, 8, 9, 11, 12, 13, 17, 19, 21, 24] Bucket Sort in Java

Input:

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BucketSort { double max_value = Collections.max(input); double min_value = Collections.min(input); double span =(max_value - min_value) / No_Of_Buckets; List < List < (); for (int i = 0; i < No_Of_Buckets; i++) { ()); } for (Double value: input) { double difference = (value - min_value) / span - ((value - min_value) / span); if (difference == 0 && value != min_value) { output.get((int)((value - min_value) / span) - 1).add(value); } else { output.get((int)((value - min_value) / span)).add(value); } } if (!bucket.isEmpty()) { Collections.sort(bucket); } } int index = 0; if (!bucket.isEmpty()) { for (Double value: bucket) { input.set(index,value); index++; } } } } public static void main(String[] args) { (); input.add(11.0); input.add(9.0); input.add(21.0); input.add(8.0); input.add(17.0); input.add(19.0); input.add(13.0); input.add(1.0); input.add(24.0); input.add(12.0); int No_Of_Buckets = 5; bucketSort(input, No_Of_Buckets); System.out.println("Sorted Output:"); for (Double value: input) { System.out.print(value + " "); } } }

Output:

Sorted Output: 1.0 8.0 9.0 11.0 12.0 13.0 17.0 19.0 21.0 24.0 Pros & Cons

Pros Cons

Perform faster computation Consumes more space compared to other algorithms

It can be used as an external sorting method Performs poorly when the data is not uniformly distributed

Buckets can be processed independently

Bucket Sort Complexity Analysis Bucket Sort’s Time Complexity:

Best Case Complexity:If all the array elements are uniformly distributed and sorted beforehand, it would require O(n) time to scatter the elements into the corresponding buckets. Then sorting each bucket using insertion sort would cost O(k). Thus the overall complexity would be O(n+k).

Average Case Complexity:For average cases, we assume the inputs are uniformly distributed. Thus the bucket sorting algorithm achieves linear time complexity of O(n+k). Here O(n) time is required for scattering the elements and O(k) time is required for sorting those elements using insertion sort.

Worst Case Complexity:In the worst case, the elements will not be uniformly distributed and concentrated over one or two specific buckets. In that case, bucket sort will work as a bubble sort algorithm. Hence, in the worst case, the time complexity of a bucket sort would be O(n^2).

Space Complexity of Bucket Sort:

Bucket sort’s space complexity is O(n*k). Here n is the number of elements and k is the number of buckets required.

How To Use Indexers In C 8 0

^ Operator − It is known as the index from the end operator.

It returns an index that is relative to the end of the sequence or collection.

It is the most compact and easiest way to find the end elements compare to earlier methods.

company.listEmployees[^2].Name = “Employee 2 Name Changed using new Syntax”;

company.listEmployees[^5].Name = “Employee 5 Name Changed using new Syntax”;

company.listEmployees[^8].Name = “Employee 8 Name Changed using new Syntax”;

Example public class Employee{    public int EmployeeId { get; set; }    public string Name { get; set; }    public string Gender { get; set; } } public class Company{    public Company(){       listEmployees.Add(new Employee       { EmployeeId = 1, Name = "SS", Gender = "Male" });       listEmployees.Add(new Employee       { EmployeeId = 2, Name = "SSS", Gender = "Female" });       listEmployees.Add(new Employee       { EmployeeId = 3, Name = "SSSS", Gender = "Male" });       listEmployees.Add(new Employee       { EmployeeId = 4, Name = "EE", Gender = "Female" });       listEmployees.Add(new Employee       { EmployeeId = 5, Name = "EEEE", Gender = "Female" });       listEmployees.Add(new Employee       { EmployeeId = 6, Name = "TTT", Gender = "Male" });       listEmployees.Add(new Employee       { EmployeeId = 7, Name = "FFF", Gender = "Male" });       listEmployees.Add(new Employee       { EmployeeId = 8, Name = "GGG", Gender = "Male" });    }    public string this[int employeeId]{       get{          return listEmployees.       }       set{          listEmployees.       }    } } class Program{    public static void Main(){       Company company = new Company();       Console.WriteLine("Name of Employee with Id = 2: " + company[2]);       Console.WriteLine("Name of Employee with Id = 5: " + company[5]);       Console.WriteLine("Name of Employee with Id = 8: " + company[8]);       System.Console.WriteLine();       Console.WriteLine("Changing names of employees with Id = 2,5,8");       company[2] = "Employee 2 Name Changed";       company[5] = "Employee 5 Name Changed";       company[8] = "Employee 8 Name Changed";       System.Console.WriteLine();       Console.WriteLine("Name of Employee with Id = 2: " + company[2]);       Console.WriteLine("Name of Employee with Id = 5: " + company[5]);       Console.WriteLine("Name of Employee with Id = 8: " + company[8]);       company.listEmployees[^2].Name = "Employee 2 Name Changed using new       Syntax";       company.listEmployees[^5].Name = "Employee 5 Name Changed using new       Syntax";       company.listEmployees[^8].Name = "Employee 8 Name Changed using new       Syntax";       System.Console.WriteLine();       Console.WriteLine("Name of Employee with Id = 2: " +       company.listEmployees[^2].Name);       Console.WriteLine("Name of Employee with Id = 5: " +       company.listEmployees[^5].Name);       Console.WriteLine("Name of Employee with Id = 8: " +       company.listEmployees[^8].Name);       Console.ReadLine();    } } Output Name of Employee with Id = 2: SSS Name of Employee with Id = 5: EEEE Name of Employee with Id = 8: GGG Changing names of employees with Id = 2,5,8 Name of Employee with Id = 2: Employee 2 Name Changed Name of Employee with Id = 5: Employee 5 Name Changed Name of Employee with Id = 8: Employee 8 Name Changed Name of Employee with Id = 2: Employee 2 Name Changed using new Syntax Name of Employee with Id = 5: Employee 5 Name Changed using new Syntax Name of Employee with Id = 8: Employee 8 Name Changed using new Syntax

How To Use Java Serversocket With Examples

Introduction to Java ServerSocket

The following article provides an outline on Java ServerSocket. In web technology, we have used front end and backend codes separately for creating web applications for the secure chúng tôi web application contains servers for receiving the client request and sent to the response for the clients’ particular request. In java technology, with the help of socket programs, we can achieve these tasks when we will send multiple requests with the help of multiple pcs, which has to be connected with the protocols like tcp and udp. We can write the server codes like ServerSocket class, connect with the specified ports, and send them to the data.

Start Your Free Software Development Course

Syntax:

The serversocket class is used for the client and server transfer process.

Server Class:

java packages import(import java.io.*,import java.net.*) class serverclassname { public static void main(String[] args) { try { --some logic— } catch() { } } }

Client class:

Java packages import(import java.io.*,import java.net.*) class clientclassname { public static void main(String[] args) { try { --some logic— } catch() { } } } How to use Java ServerSocket?

Java server socket connections will use the two types of protocols for sent and receive the data.

TCP(transfer control protocol) and udp(user datagram protocol) will use the sockets class to transfer the data.

We also see some difference between these two protocols while we use in the socket class when we use udp, it means is a connection less, and there are no sessions for storing the log data regarding client and server transmissions, but in tcp, it is a connection-oriented, so the client and server have the session storages in the log folders.

The socket programs will be used for communications between the web applications running with the different jre.

The serversocket class are mainly with the connection-oriented socket programs.

When we connect the applications with the help of socket, we need to get the information’s like IP Address of the servers and port numbers which has to be connected with the applications for a specified way so that the data transmission will not be interpreted.

Basically, the socket class between client and server is one-way data transmission. The client will send the request messages to the server, servers read the client messages, and send the response to the client, or else it will display the data on the client screen like browsers.

So that we will use two types of java net classes are used a socket and serversocket classes; the socket class is responsible for client-server communications, serversocket class is used for server-side applications it will authenticate the request from the client-side until the client machine is connected with the socket class after the successful connections it will return the socket class instance in the server-side applications.

Examples of Java ServerSocket

Given below are the examples:

Example #1

Code: Client Example

import java.io.IOException; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class clientSample { public static void main(String arg[]) throws UnknownHostException,IOException { int n,n1; String s; Scanner sc=new Scanner(System.in); Socket s1=new Socket("127.0.0.1",1408); Scanner sc1=new Scanner(s1.getInputStream()); System.out.println("Enter any port numbers"); n=sc.nextInt(); PrintStream p=new PrintStream(s1.getOutputStream()); p.println(n); n1=sc1.nextInt(); System.out.println("Square of the given port number is: "+n1); } }

Output:

import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class ServerSample { public static void main(String[] args)throws IOException { int n,n1; String s; ServerSocket s1=new ServerSocket(1408); Socket s2=s1.accept(); Scanner sc=new Scanner(s2.getInputStream()); s=s2.toString(); n =sc.nextInt(); n1=n*n; PrintStream p=new PrintStream(s2.getOutputStream()); p.println(n1); System.out.println("Server started and working.. "); } }

Output:

Example #2

Code: Client Example

import java.net.*; import java.io.*; public class clientSample { public static void main(String[] args) throws Exception { try{ Socket s=new Socket("127.0.0.1",8888); DataInputStream d=new DataInputStream(s.getInputStream()); DataOutputStream out=new DataOutputStream(s.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String client="",server=""; while(!client.equals("")){ System.out.println("Enter the number :"); client=br.readLine(); out.writeUTF(client); out.flush(); server=d.readUTF(); System.out.println(server); } out.close(); out.close(); s.close(); }catch(Exception e){ System.out.println(e); } } }

Code: Server Client

import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; class ServerClients extends Thread { Socket sockets; int clients; int squre; ServerClients(Socket s,int count){ sockets = s; clients=count; } public void run(){ try{ DataInputStream inStream = new DataInputStream(sockets.getInputStream()); DataOutputStream outStream = new DataOutputStream(sockets.getOutputStream()); String client="", server=""; while(!client.equals("")){ client=inStream.readUTF(); System.out.println("From Client side-" +clients+ ": Number of client is :"+client); squre = Integer.parseInt(client) * Integer.parseInt(client); server="From Server to Client request-" + clients + " Square of the client " + client + " is " +squre; outStream.writeUTF(server); outStream.flush(); } inStream.close(); outStream.close(); sockets.close(); }catch(Exception ex){ System.out.println(ex); }finally{ System.out.println("Client -" + clients + " exit!! "); } } }

Code: Server Example

import java.net.*; import java.io.*; public class ServerSample { public static void main(String[] args) throws Exception { try{ ServerSocket s=new ServerSocket(8888); int count=0; System.out.println("Server is Started ...."); while(true){ count++; Socket socket=s.accept(); ServerClients sc = new ServerClients(socket,count); sc.start(); } }catch(Exception e){ System.out.println(e); } } }

Output:

Example #3

Code: Client Program

import java.net.*; import java.io.*; public class ClientMain { public static void main (String[] args ) throws IOException { int size=1022388; int bytess; int c = 0; Socket sockets = new Socket("localhost",12345); byte [] bytes = new byte [size]; InputStream in = sockets.getInputStream(); FileOutputStream out = new FileOutputStream("F:\copy.doc"); BufferedOutputStream b = new BufferedOutputStream(out); bytess= in.read(bytes,0,bytes.length); c = bytess; do { bytess = in.read(bytes, c, (bytes.length-c)); } b.write(bytes, 0 , c); b.flush(); b.close(); sockets.close(); } }

Code: Server Program

import java.net.*; import java.io.*; public class Main { public static void main (String [] args ) throws IOException { ServerSocket serverSockets = new ServerSocket(12345); Socket sockets = serverSockets.accept(); System.out.println("Server connection Accepted : " + sockets); File f = new File ("F:\Sample.docx"); byte [] bytes = new byte [(int)f.length()]; FileInputStream input = new FileInputStream(f); BufferedInputStream b = new BufferedInputStream(input); b.read(bytes,0,bytes.length); OutputStream output = sockets.getOutputStream(); System.out.println("Sending Files..."); output.write(bytes,0,bytes.length); output.flush(); sockets.close(); System.out.println("File transfer complete"); } }

Output:

Conclusion

In java programming technology, the package is called java.net.* In that each version of java it may vary the classes in the package the server socket connection is a basic networking feature for file transmission, upload and even though we have sent an email from one client to another client with the help of socket connections

Recommended Articles

This is a guide to Java ServerSocket. Here we discuss the introduction, how to use Java ServerSocket, along with respective examples. You may also have a look at the following articles to learn more –

How To Use Html Schriftart With Examples

Introduction to HTML Schriftart

Web development, programming languages, Software testing & others

Syntax:

Htmlfonts(Schriftart) is using some style attributes in CSS styles, and also using font tag we declared the font face, size, and colors.

The above code is one of the basic syntaxes for the html fonts declared and used in the web pages. We also displayed the fonts in different style attributes like bold, italic and underlined views.

How to Use Html Schriftart?

The annotation-based html tag is used in the CSS styles on the side of the browser; it will load the default one in the HTML web page it may be created an issue. If we call the external fonts in the web browsers using the style like @font-face, whenever the user use the text, it will convert automatically to the given font styles whichever we assign the fonts in the css it will be used for the completely invisible side in the front end. In some type of browsers will be waiting for loading the custom fonts in the web pages; it may take some time to load the web page; normally, it will take 3 seconds to display the web pages.

In Webkit type of browsers like safari, android browsers, and blackberry mobile browsers, it may take upto 30 seconds over time to load the web pages. Some times custom fonts will represent in potentially some failure in the usable sites. If we use css styles, it will look appearance more flexible, user-friendly even we download any other files it also looks pretty and very simple to use on the web pages.

In most browsers, the default font size is 3, and in the majority of the web sites, the text values will be the range from 2 to 3; it may vary when compared to each browser and web sites. The font size will be declared into two different categories 1. Absolutely and chúng tôi Absolute sizes range between 1 and 7; the values will have differed when the user browsers compatibility. We can also resize the fonts after the declaration of the font sizes it will affect the user texts in the web pages also differ it will adapt the user preferences that is the text size will be displayed somewhat different from user expectation it will show like high, very high or low text will be shown as the above types. If we set the font size will be very less length it’s difficult to read the web pages on the user end.

If we use high font length, then the web page will be a continuation from another page; the user will also scroll the web pages the navigation it’s needed for the front end. The text font size will be user end, so it will choose the user point of view it will show the normal and the appearance will be more sophisticated in the front end. Whenever we create a web page, it will intend to make them accessible in the www consortium; then, it will permit us to display the web page in globally.

Generally, font face values will be some fixed one like “Times New Roman, Comic sans MS, Arial, Calibri”, etc. the above 3 to 4 font faces will be used for most of the web sites even though the “Schriftart” this font will be used in the web page documents. We can set the font face with the help of face attributes, but we should also be aware that if the user does not log in and view the pages in the browsers because the font styles should be installed in the user pcs then only it will be displayed in the browser screen. If the font is not installed, the user will see the screen using the default font, which already installed on the pc.

Examples to Implement HTML Schriftart

Below are the examples mentioned:

Example #1

Code:

Example #2

Code:

Output:

Example #3

Welcome User Welcome To My Domain

Output:

Explanation to the above examples: In the above three examples, we discussed the font sizes with different ranges; the above three outputs are executed in the chrome browsers the font size whatever we mention in the code it will be displayed in the browser the final example we have seen the font size, styles, and colors.

Conclusion

We have seen the html schriftart(font) is angerman language fonts; we will use the fonts to translate the html predefined tags to convert the german language, but the functionalities of the fonts are to be the same as we discussed in the font features, colors, and sizes. In CSS, it will declare in the font style attributes it will mention all the font behaviors.

Recommended Articles

This is a guide to HTML Schriftart. Here we discuss the introduction to Html Schriftart with examples for better understanding. You can also go through our other related articles to learn more –

Update the detailed information about C# Queue With Examples: What Is C# Queue And How To Use? on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!