TCP Programming in Java


Server.java
===========
 
 import java.io.*;
 import java.net.*;
 public class Server
 {
  ServerSocket ss;
  Socket s;
  BufferedReader bin;
  PrintWriter pw;
  String msg,EXIT="exit";
  public Server()
  {
   try
   {
    ss=new ServerSocket(800);
    s=ss.accept();
    bin=new BufferedReader(new InputStreamReader(System.in));
    pw=new PrintWriter(s.getOutputStream(),true);
    while(true)
    {
     msg=bin.readLine();
     if(EXIT.equals(msg))
     {
      pw.println("exit");
      System.exit(0);
     }
     else
     {
      pw.println(msg);
     }
    }
   }
   catch(Exception e)
   {
    System.out.println("Server Failed");
   }
  }

 }

   Client.java
   ===========
 
 import java.io.*;
 import java.net.*; 

public class Client
 {
  Socket s;
  BufferedReader br;
  String msg;
  public Client()
  {
   try
   {
    s=new Socket("localhost",800);
    br=new BufferedReader(new InputStreamReader(s.getInputStream()));
    while(true)
    {
     msg=br.readLine();
     if(msg.equals("exit"))
     {
      System.exit(0);
     }
     else
     {
      System.out.println(msg);
     }
    }
   }
   catch(Exception e)
   {
    System.out.println("Client Failed");
   }
  }

 }

RunServer.java
==============
import Server;
public class RunServer
{
 public static void main(String[] args)
 {
  Server server=new Server();
 }

RunClient.java
==============
import Client;
public class RunClient
{
 public static void main(String args[])
 {
  Client client=new Client();
 }
}

Post a Comment

0 Comments