Thursday, December 16, 2010

TCP Server-Client Application

Server Application

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

public class TCPServer{
public static void main(String args[]){
int port=8088;
ServerSocket ser1=null;
PrintWriter pr=null;
BufferedReader br=null;
String str;
Socket soc1=null;

try{
ser1=new ServerSocket(port);
}catch(IOException e){
System.exit(0);
}
while(true){
try{
soc1=ser1.accept();     
        pr=new PrintWriter(new OutputStreamWriter(soc1.getOutputStream()));
pr.println("Client is connected");
        br=new BufferedReader(new InputStreamReader(soc1.getInputStream()));

while((str=br.readLine()) != null)
   System.out.println(str);

if(soc1!=null){
pr.close();
soc1.close();                
}
}catch(IOException e) {
System.out.println(e);
}
}
}
}

Client Application

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

public class TCPClient{
public static void main(String args[]){

Socket soc1;
BufferedReader br;
String str;
PrintWriter pr=null;
try{
soc1=new Socket("127.0.0.1",8088);        
        br=new BufferedReader(new InputStreamReader(soc1.getInputStream()));

while((str=br.readLine()) != null)
   System.out.println(str);
        
        pr=new PrintWriter(new OutputStreamWriter(soc1.getOutputStream()));
pr.println("Server is connected");

br.close();
soc1.close();
pr.close();
}catch(ConnectException e){
 System.out.println(e);
}catch(IOException e){
System.out.println(e);
}       
}
}

No comments:

Post a Comment