Skip to main content

Java Socket Basics(Socket Programming in Java) Part-1(TCP)

Hi friends,
This post is about the Java Socket Programming. I know there are a lot of article and post are available over the internet about Java Socket Programming but all the content like the perquisite of socket programming, example of TCP and UDP is here at one place.

So first question, what is TCP and UDP and what is the difference between these two. See below-


Perquisite:-
There are several things related to socket programming in java which you must not ignore...
  • Do not forget to close the stream or socket connection when the related task is done.
  • Recommended to use try with resource whenever it is possible.
  • If you are not dealing with try with resource, then it is highly recommended to close all the resources and related sockets in finally block.

java.net.SocketException: Too many open files:: 

This is an usual exception which generally thrown by Socket. So the question is What may be the possible reasons for  this exception. So go through the following listings. Possibly...

  • You have forgot to close the resources when their task done.
  • You have forgot to close socket connection when you done with it.
  • May be Number of open file descriptors per process is less than it required by your application.
  • TIME_WAIT state(timeout) of your operating system is more than expected. 
Possible ways to deal with 'java.net.SocketException: Too many open files':-
  • Do not forget to close the stream or socket connection when the related task is done.
  • Recommended to use try with resource whenever it is possible.
  • If you are not dealing with try with resource, then it is highly recommended to close all the resources and related sockets in finally block.
  • Reduce TIME_WAIT state of your operating system.
  • Increase Number of open file descriptors per process in your operating system. You can check Number of open file descriptors per process(In Linux) using ulimit -a command.

TCP Sample:-
We are going to create an small sample which contains two classes.
  1. SocketServer.java:- This is a server class. Means this class will serve the purpose of socket connection. ServerSocket is the class which helps for TCP socket connection. This required a system port number on which client can communicate and send data to server.
  2. SocketClient.java:- This is client class. This serves the purpose of client which will communicate to server and send data to server. Socket is the class which helps for TCP client connection. This requires Server's IP(URL) and the Server's port number on which Server has open the socket connection.
SocketServer.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketSever {

 public static void main(String[] args) {

  try {
   System.out.println("Starting server...");
   ServerSocket serverSocket = new ServerSocket(8086);
   System.out.println("Server started. Waiting for client connection...");
   Socket socket = serverSocket.accept();
   System.out.println("Client connected. Reading data from client...");
   InputStream inputStream = socket.getInputStream();
   OutputStream outputStream = socket.getOutputStream();
   PrintWriter printWriter = new PrintWriter(outputStream, true);
   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

   String receiveMessage;
   if ((receiveMessage = reader.readLine()) != null) {
    System.out.println("Data sent from client : " + receiveMessage);
   }
   System.out.println("Sending data back to client..");
   printWriter.println("Hello Client");
   printWriter.flush();
   socket.close();
   serverSocket.close();
   System.out.println("Shuting down server...");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}



SocketClient.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {
 public static void main(String... strings) {
  try {
   System.out.println("Connecting to server...");
   final Socket socket = new Socket("localhost", 8086);
   System.out.println("Connected to server");

   final OutputStream outputStream = socket.getOutputStream();
   final PrintWriter printWriter = new PrintWriter(outputStream, true);
   final InputStream inputStream = socket.getInputStream();
   final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
   System.out.println("Writting data on server...");
   printWriter.println("Hello Server");
   printWriter.flush();
   String receiveMessage;
   System.out.println("Reading data from server...");
   if ((receiveMessage = reader.readLine()) != null) {
    System.out.println(receiveMessage);
   }
   socket.close();
   System.out.println("Closing client connection");
  } catch (Exception e) {
   System.out.println("Server is unable to reach");
   e.printStackTrace();
  }
 }
}

This example works as Client->Server and Server->Client mechanism. Means this example describes two way communication between Client and Server.

Note:- You can modify these classes little bit and this will start working as Chat Application. Just put the read and write logic inside an infinite while loop and send data to server or client after reading the message from console. Please try this yourself and let me know. You gonna develop a Simple Chat Application :)

So this was all about for TCP. In next post we will see a sample about UDP.

Hope this will help you. Suggestions are most welcome. Keep visiting my blog :)

Comments

Popular posts from this blog

JavaFX WebView- Creating Browser Sample

Hi Friends, In this post, i am going to give an overview about JavaFX WebView . This is an embedded browser component which is based on WebKit . If allow you to use Css, JavaScript, HTML5 and more to customise your embedded browser. The embedded browser enables you to perform the following tasks in your JavaFX applications: Render HTML content from local and remote URLs Obtain Web history Execute JavaScript commands Perform upcalls from JavaScript to JavaFX Manage web pop-up windows Apply effects to the embedded browser  I am going to provide and explain you a sample example to create your embedded browser. This is a JavaFX sample example. if you want to take an introduction about JavaFX please visit my previous blog . I have use IntelliJ Idea IDE for this example. You can visit this link  to understand how to create JavaFX application. I am attaching the project structure image below- In this sample- we have two java class. First

Working with MPAndroidChart (how to create Bar Chart using MPAndroidChart)

Hi Friends, In this tutorial i am going to show, "How to create Bar Chart using MPAndroidChart". There is a lot of libraries for creating charts in android like AChartEngine, MpAndroidChart, AndroidPlot etc. Your first question may be, Why MPAndroidChart. So MpAndroidChart provides better animation functionality and easy to use in comparision. Using  MPAndroidChart library  we can draw a: ·          Simple Bar Chart ·          Grouped Bar Chart ·          Horizontal Bar Chart ·          Simple Line Chart ·          Line Chart with Cubic Lines ·          Grouped Line Chart ·          Combined Line and Bar Chart ·          Pie Chart ·          Scatter Chart ·          Candlestick Chart ·          Radar Chart Here we will create Simple Bar Chart with multiple color based on ranging. Ok We start with coding part now. First of all create your project in Android Studio and add gradle dependency for  MPAndroidChart library  into y

app-policy

PRIVACY POLICY Last updated April 19, 2023 This privacy notice for Team CoderzDuniya ( " Company ," " we ," " us ," or " our " ), describes how and why we might collect, store, use, and/or share ( " process " ) your information when you use our services ( " Services " ), such as when you: Download and use our mobile application ( Revenue Calculator) , or any other application of ours that links to this privacy notice Engage with us in other related ways, including any sales, marketing, or events Questions or concerns?  Reading this privacy notice will help you understand your privacy rights and choices. If you do not agree with our policies and practices, please do not use our Services. If you still have any questions or concerns, please contact us at droidamar007@gmail.com . SUMMARY OF KEY POINTS This summary provides key points from our privacy notice, but you can find out more details about any of these t