Client-Server Using TCP Connection

Create two class Client & Server for communication using tcp connection in java

 
import java.io.*;
import java.net.*;
public class server 
{
 public static void main(String[] args)throws Exception 
 {
  ServerSocket ss=new ServerSocket(7777);
  Socket s=ss.accept();
  System.out.println("Conncetion Established");
  OutputStream obj=s.getOutputStream();
  PrintStream ps =new PrintStream(obj);
  String str="Hello Client";
  ps.println(str);
  ps.println("Bye");
  ps.close();
  ss.close();
  s.close();
 }
}

import java.net.*;
import java.io.*;
public class client1 
{
 public static void main(String[] args) throws Exception 
 {
  Socket s = new Socket("localhost",7777);
  InputStream obj = s.getInputStream();
  BufferedReader br=new BufferedReader(new InputStreamReader(obj));
  String str;
  while((str=br.readLine())!=null)
  {
   System.out.println("From Server:"+str);
  }
  br.close();
  obj.close();
  s.close();
 }
}

Output

Client's Output
Server's Output

0 comments:

Post a Comment