Full width home advertisement

Electronics Hub

Internet of Networks

Post Page Advertisement [Top]

Q. Implement the Client-Server Communication by writing a program in Java using TCP Socket.

Ans.

Server side program:


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

class mat
{
public static void main(String args[])
{
String data= "Network Lab";
try
{
  ServerSocket serv= new ServerSocket(1234);
  Socket skt= serv.accept();
  System.out.println("Server is connected\n");
  PrintWriter out= new PrintWriter(skt.getOutputStream(),true);
  System.out.println("Sending string:"+data+"\n");
  out.print(data);
  skt.close();
  out.close();
  serv.close();
 }
  catch (Exception e)
  {
   System.out.println("Oops! didn't work \n");
   }
  }
 }

Client side program:


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

class lab
{
 public static void main(String args[])
{
  try
    {
     Socket srt= new Socket(InetAddress.getLocalHost(),1234);
     BufferedReader in= new BufferedReader(new InputStreamReader(srt.getInputStream()));
     System.out.println("Receiving String");
     while(!in.ready())
     {
     }
   System.out.println(in.readLine());
   System.out.println("\n");
   in.close();
   }
   catch (Exception e)
  {
   System.out.println("Oops! didn't work out as well \n");
   }
  }
 }

Output:

Server side:

javac mat.java (//enter) 
java mat (//enter)

Server is connected
Sending string: Network Lab

Client side:

javac lab.java (//enter)
java lab (//enter)

Receiving String
Network Lab

socket programming, socket io
Free image Downloaded from unsplash.com

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Sriparna Sarkar