Socket Programming TCP/IP

Chat Client

import java.io.*;

import java.net.*;

public class chatclient

{

public static void main(String args[])

{

String line;

String myline;

BufferedReader in=null;

try

{

Socket s=new Socket(“localhost”,8182);

DataInputStream dis=new DataInputStream(s.getInputStream());

PrintStream out=new PrintStream(s.getOutputStream());

in=new BufferedReader(new InputStreamReader(System.in));

do

{

line=dis.readLine();

System.out.println(“The Message from the Server is  : “+line);

System.out.print(“Enter the Message to the server : “);

myline=in.readLine();

out.println(myline);

}while(myline.equalsIgnoreCase(“quit”)==false);

out.close();

dis.close();

}

catch(Exception e)

{

System.out.println(“Unknown Error”+e);

}

}

}


Chat Server

import java.io.*;

import java.net.*;

public class chatserver

{

public static void main(String args[])

{

String line;

int i=1;

String myline;

BufferedReader in=null;

try

{

ServerSocket ss=new ServerSocket(8182);

System.out.println(“Server is started”);

in=new BufferedReader(new InputStreamReader(System.in));

Socket s=ss.accept();

DataInputStream dis=new DataInputStream(s.getInputStream());

PrintStream out=new PrintStream(s.getOutputStream());

do

{

System.out.print(“Provide message to client : “);

myline=in.readLine();

out.println(myline);

line=dis.readLine();

System.out.println(“Received from client      : “+line);

}while(myline.equalsIgnoreCase(“quit”)==false);

out.close();

dis.close();

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Advertisements