Simplified : Client_Server – Socket Programming in Java

Client_Server – Socket Programming in Java

java socket programming



Client -server communication

At a basic level, network-based systems consist of a server , client , and a media for communication. A computer running a program that makes a request for services is called client  machine. A computer running a program that offers requested services from one or more clients is called  server machine.

Client-Server Architcture


What are Sockets?

In Client-Server architecture, you have two processes (running client-Server programs) that want to communicate with each other. For that, they have to establish a communication link between themselves. There is a network available,they just need to connect to this network , for this they use sockets.

Sockets in client server architecture

A socket is one endpoint of a two-way communication link between two programs running on the network.

An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.
The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program on the network. 

How do I Open a Socket ?

If you are programming a client, then you would open a socket like this:
 Socket s;
s
= new Socket("Machine name", PortNumber);
Where Machine name is the machine you are trying to open a connection to, and Port-Number is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root). These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!


It is a good practice to handle exceptions. The above can be written as:

    Socket s;
try {
s
= new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
If you are programming a server, then this is how you open a socket:

    ServerSocket ss;
try {
ss
= new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.

Socket clientSocket = null;
try {
serviceSocket
= ss.accept();
}
catch (IOException e) {
System.out.println(e);
}

How do I create Buffered Reader?

Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. 
    try {
BufferedReader br = new BufferedReader(new InputStreamReader(ss.getInputStream()));

}
catch (IOException e) {
System.out.println(e);
}

How do I create an output stream?

On the client side, you can create an output stream to send information to the server socket using the class  of java.io:
    PrintStream output;
try {
OutputStream ostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);

}
catch (IOException e) {
System.out.println(e);
}
The class DataOutputStream allows you to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.

How do I Close a Socket ?

On the client side:

    try {
output
.close();
input
.close();
s
.close();
}
catch (IOException e) {
System.out.println(e);
}

On the server side:

    try {
output
.close();
input
.close();
ss
.close();
}
catch (IOException e) {
System.out.println(e);
}
Let’s see java code for one-way communication using socket programming:

Client Side Code:
import java.net.Socket; 
import java.io.OutputStream;
import java.io.DataOutputStream;

public class SCPTL
{
public static void main(String args[]) throws Exception
{
Socket sock = new Socket("localhost", 5000);
String message1 = "Learn-Intern-Certify from SCPTL";

OutputStream ostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);
dos.writeBytes(message1);
dos.close();
ostream.close();
sock.close();
}
}
Server Side Code:
import java.net.ServerSocket;            
import java.net.Socket;
import java.io.*;

public class SERVER
{
public static void main(String args[]) throws Exception
{
ServerSocket sersock = new ServerSocket(5000);
System.out.println("server is ready"); // message to know the server is running

Socket sock = sersock.accept();

BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));

String message2 = br.readLine();
System.out.println(message2);
sock.close(); sersock.close();
}
}

Output:

Client:

Client side output
Server:

Server side output

Want to learn more about java?

The T-Mobile HTC U11 Life is getting Android 8.0 Oreo (updated)

Update (12/18/17): Just about three weeks ago, the unlocked HTC U11 Life was upgraded to Android 8.0 Oreo. Now, the T-Mobile variant is receiving the update as well. T-Mobile is the only carrier in the United States to carry the HTC U11 Life so between it and the unlocked versions, pretty much everyone should be updated to Oreo at this point.

HTC warns that this is a pretty large download so you’ll need to connect to Wi-Fi before you start. As a reminder, Oreo brings background limits on apps that help to save power, smart text selection, grouped notifications, and picture-in-picture mode, among other features. To read more about Oreo, check out our review here.

Original article (11/30/17): The HTC U11 Life was introduced earlier this month, arriving on the Android One program in global markets (with almost stock Android), while those in the US received a variant with HTC’s Sense UI. The device launched with Android Oreo outside of the US, meaning those residing in the States were left waiting for the latest Google software, but HTC assured that it wouldn’t be far off.

Today, I bring good news as the US unlocked U11 Life is now said to be receiving Oreo. HTC Vice President of Product Manager Mo Versi delivered the news via a Tweet published a couple of hours ago. Versi said that the update would be available “starting today,” but we don’t know how long it could take to hit individual devices.

HTC has been on a roll with its rollouts this week, having upgraded the regular HTC U11 flagship to Oreo just a couple of days ago. Here’s hoping the speedy updates continue for the rest of its smartphone lineup.

Check out our full HTC U11 Life review at the link and visit our dedicated Android 8.0 Oreo update page to find out more about HTC’s schedule.

3D printing larger objects

Since I bought my 3D printer I have printed hundreds of miniatures for my Dungeons & Dragons game. The miniatures are in a classic 1 inch = 5 feet that is 1:60 scale. So a typical medium sized miniature has a 25 mm base and is around 28 mm tall. As I have written earlier, the main problem of printing objects that size is that printing anything less than 1 mm thick tends to fail, so I had to “fatten” some miniatures or give them oversized weapons to work. Now that I have a good selection of miniatures, I am more often printing larger objects, and the challenges are different.

Now “larger objects” on my 3D printer are limited to 150 mm in any dimension due to the size of the printer itself. Over the last month I printed several objects that were at or close to that limit: Two dice towers, a hinged box, a card tray and two card holders for the 7th Continent, and JoyCon holders for the Nintendo Switch. Apart from the box, which was more of a tech demo to show that you can print a hinged object in one piece, the other objects would be either hard to get anywhere, or be much more expensive. Thus there is some utility to printing these larger objects yourself. The 3D printer also automatically makes items hollow, filled with some honeycomb structure, so a bulky 3D printed object is quite lightweight.

While with larger objects there are no more problems with too thin parts, the main downside of these objects is that the uneven surface is far more prominent. If you are used to holding plastic items in your hand which have a smooth and shiny surface, the 3D printed objects are notably different. Along the Z-axis the layer structure is very visible. And on inner surfaces where the printer had to move across empty space to get to the other side of the object there are irregular imperfections. To some extent you can clean the object up using a sanding sponge. But unless you want to spend hours sanding the object will never be totally smooth and shiny like a commercial injection-molded item.

I still don’t believe in a future where we all just 3D print everything we need instead of buying mass-produced items. However there are a few niche applications where a 3D printer can produce a larger object of some use.

As the Trump Administration Continues to Threaten the Planet, This Is No Time to Be Complacent

As the days get darker, we must keep the flame burning.

Before he died on November 7, 2016, the great poet Leonard Cohen offered a prophetic warning in his final album’s title song: “You want it darker / We kill the flame.” As we near the northern hemisphere’s longest night of the year, it seems like a monumental challenge to keep the flickering flame from being extinguished.

In the U.S., human rights, environmental protections and social services are being snuffed out by executive order. Angry rhetoric from an administration that appears to thrive on division is fueling racial tensions. As drought-fueled fires rage, storms become more intense and unpredictable and flooding devastates communities, much of the world outside the United States plans how to meet commitments under the Paris Agreement. Yet the fossil fuel industry and its government sycophants continue to destroy ecosystems in their race to exploit every bit of climate-altering product they can before shrinking markets halt their rampage.

Even governments that say they’re committed to tackling climate change continue to promote pipelines, fracking and other fossil fuel projects and infrastructure. We also face the spectacle of two mad nuclear-armed heads of state trading childish insults, inching us closer to catastrophic confrontation.

Another great poet, William Butler Yeats, wrote presciently in 1919: “The blood-dimmed tide is loosed, and everywhere / The ceremony of innocence is drowned / The best lack all conviction, while the worst / Are full of passionate intensity.”

It’s not really true that the “best lack all conviction.” But as the days get darker, it sometimes feels overwhelming, hopeless.

We must keep the flame burning.

The light will return to this part of the world and the days will get longer, but we must act to make our lives brighter. The “passionate intensity” (or maybe just banal indifference to suffering) of those who would impose misery on many for the benefit of the few may be little more than the death throes of an outdated, destructive order. But it’s no time to be complacent. We must show that we shine brighter. Knowledge, kindness and solidarity can overcome ignorance and fear.

This truth is coming to light as more and more people reject the forces of darkness. #MeToo. Black Lives Matter. Idle No More. Women are speaking out against those who have oppressed them through rape, abuse and systemic sexism. People of color are standing up to the violence, hatred and inequality they have faced in countries claiming to value freedom and equality. Indigenous Peoples are demonstrating their knowledge and power and demanding an end to colonial oppression. Business people, religious leaders, politicians and citizens are demanding action on climate change and other environmental challenges. People everywhere are developing solutions to the problems we have caused through ignorance and avarice.

We must also work for better education, at home and throughout the world. Stabilizing population growth requires education for women and families, along with access to birth control and family planning. Democracies function best when people cast their votes and base their decisions on facts, critical thought and understanding rather than tribalism and rigid ideology. Those who have learned how to critically assess the overabundance of information that floods our daily lives are in a better position to contribute to positive change.

For many cultures, the winter solstice is a time to reflect, regroup and rededicate. As the light slowly returns, it’s a period of renewal and eventual rebirth. It’s a good time to celebrate that which holds true meaning and brings real happiness in life: friends, family, nature, connection. It’s also a time to reach out to help those who are less fortunate.

Every good deed, every positive act, helps the flame burn a little bit brighter. No matter how small or insignificant our contributions may seem, when we do good in the world, it adds up—and it will eventually overcome the darkness. Even an unconditional smile given to a stranger can cheer that person, who may then offer smiles to others, multiplying the effect and spreading joy.

As we near the solstice and enter the holiday season, I and the David Suzuki Foundation staff wish you peace and happiness for this year and the days to come. Let us all shine our lights to make the world a brighter, better place for all.

This article was written by David Suzuki with contributions from David Suzuki Foundation Senior Editor Ian Hanington and originally published by the David Suzuki Foundation.

 

 

Related Stories

  • Wall of Shame: Top 10 Climate Deniers in the Trump Administration
  • How the Right-Wing Media Totally Distorted Positive News on Climate Change
  • Holiday Buyers Beware: 9 Retailers Who Got an ‘F’ Rating for Failing to Take Action on Dangerous Chemicals in Consumer Products

Test Your PL/SQL Fundamentals

In Oracle database management, PL/SQL is a procedural language extension to Structured Query Language (SQL). The purpose of PL/SQL is to combine database language and procedural programming language. The basic unit in PL/SQL is called a block, which is made up of three parts: a declarative part, an executable part, and an exception-building part.
Test your PL/SQL knowledge by solving following 49 MCQ’S

Loading…