×

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

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

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...

3 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.