×

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

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.