×

Java Network Programming (Socket Programming in Java)

JAVA NETWORK

Network programming is used to execute programs across multiple machines that are connected by a network.

The java.net package contains a collection of classes and interfaces that provide this functionality.

The java.net package provides support for the two common network protocols:

  • TCP - TCP (Transmission Control Protocol) is for reliable communication between two applications. It is used over the Internet protocol, known as TCP/IP.
  • UDP - (User Datagram Protocol) is a connectionless protocol that is used to transmit data packets between applications.

The socket provides the way to communicate between two computers using TCP. The client creates a socket on its end and support for the two common network protocols:

  • TCP - TCP (Transmission Control Protocol) is for reliable communication between two applications. It is used over the Internet protocol, known as TCP/IP.
  • UDP - (User Datagram Protocol) is a connectionless protocol that is used to transmit data packets between applications to connect that socket to a server.

There are two types of TCP socket present in Java: server and clients.

The server socket class acts as a listener which waits for clients to connect.

The client's socket class is for clients. It initiates the exchange protocol and connects to the server.

The creation of socket object implicitly establishes a connection between the client and server.

Constructors client sockets

Socket(String hostName, int port) throws UnknownHostException, IOException

It creates a socket connected to the named host and port.

Socket(InetAddress ipAddress, int port) throws IOException

It creates a socket using a preexisting InetAddress object and a port.

Useful Methods

Modifier and Type

Method

Description

InetAddress

getInetAddress( )

It returns the InetAddress associated with the Socket object. It returns null if the socket is not connected.

int

getPort( )

It returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected.

int

getLocalPort( )

It returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound.

Modifier and Type

Method

Description

InputStream

getInputStream( )

throws IOException

It returns the InputStream associated with the invoking socket.

OutputStream

GetOutputStream( )

throws IOException

It returns the OutputStream associated with the invoking socket.

We can gain access to the input and output streams associated with a Socket by using getInputStream( ) and getOuptutStream( ) methods. These methods can throw an IOException if the socket has been invalidated by a lost connection.

Java Socket Programming Example

This is the client class.

import java.io.DataOutputStream;
import java.net.Socket;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6061);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Connected to server");
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

This is a server class.

import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6061);
Socket s = ss.accept();// establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message = " + str);
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:

message = Connected to server

Related Topics

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.