You are here: Home / Topics / Client \ Server program using Socket and ServerSocket class in Java

Client \ Server program using Socket and ServerSocket class in Java

Filed under: Java on 2023-10-25 06:51:11

// Client \u2013 Server program using Socket and 
// ServerSocket class.

// File-1 : Server.java
import java.io.*;
import java.net.*;

public class Server 
{
public static void main( String[ ] args ) 
{
 try 
 {
  ServerSocket ss = new ServerSocket(5000);
  Socket sc = ss.accept( );
  
  InputStream is = sc.getInputStream();
  InputStreamReader isr = new InputStreamReader( is );
  BufferedReader in = new BufferedReader( isr );
  PrintWriter out = new PrintWriter(sc.getOutputStream(), true);
  String str = in.readLine();
  out.println(" Application Name : " + str);
  sc.close();
 }
 catch (Exception e) 
 { }
}
}

// File-2 : Client.java
// The Client Socket Program.

import java.net.*;
import java.io.*;

class Client 
{
public static void main( String args[ ] ) throws Exception 
{
 int ch;
 // IP address of Server PC => 192.168.1.2
 Socket sc = new Socket("192.168.1.2", 5000);
 // Host name of Server PC => PC1
 // or Socket sc = new Socket("PC1", 5000);
 
 InputStream in = sc.getInputStream();
 OutputStream out = sc.getOutputStream();
 String str = "Java Programming Examples.\n";
 byte buf[ ] = str.getBytes();
 out.write(buf);

 while ((ch = in.read()) != -1) 
 {
  System.out.print((char) ch);
 }
 sc.close();
}
}


Output:(for File: Server.java)

D:\Java Examples\java Server

 

Output:(for File: Client.java)

D:\Java Examples\java Client
Application Name : Java Programming Examples.

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.