Wednesday, October 24, 2012

81. TCP/UDP CLIENT SERVER PROGRAM IN JAVA


//CLEINT PROGRAM

import java.io.*;
import java.net.*;
import java.lang.*;
class client
{
public static void main(String a[])throws IOException
{
Socket s=new Socket("LocalHost",8000);
DataInputStream in=new DataInputStream(s.getInputStream());
DataInputStream inn=new DataInputStream(System.in);
PrintStream dos=new PrintStream(s.getOutputStream());
while(true)
{
String str=in.readLine();
System.out.println("msg received:"+str);
if(str.equals("end"))
{

s.close();
break;
}
System.out.println("enter the msg to send: ");
String str1=inn.readLine();
dos.println(str1);
if(str1.equals("end"))
{
s.close();
break;
}
}
}
}

//SERVER PROGRAM

import java.io.*;
import java.net.*;
import java.lang.*;
class server
{
public static void main(String a[])throws IOException
{
ServerSocket ss=new ServerSocket(8000);
Socket s=ss.accept();
PrintStream dos=new PrintStream(s.getOutputStream());
DataInputStream in=new DataInputStream(System.in);
DataInputStream inn=new DataInputStream(s.getInputStream());
while(true)
{
System.out.println("enter the msg to send: ");
String str=in.readLine();
dos.println(str);
if(str.equals("end"))
{
ss.close();
break;
}
String str1=inn.readLine();
System.out.println("msg received: \n"+str1);
if(str1.equals("end"))
{ss.close();
 break;
}
}
}
}

OUTPUT:
//SERVER OUTPUT
enter the msg to send: hii
msg received: heya
enter the msg to send: hiii nice to see u..
msg received: same here..

//CLIENT OUTPUT:-
msg received: hii
enter the msg to send: heya
msg received: hiii nice to see u..
enter the msg to send: same here..