import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class SimpleServer { private static ServerSocket server; private static int port=3234; public static void main(String[] args) { // TODO Auto-generated method stub try{ server=new ServerSocket(port); } catch(IOException ioEx) { System.out.println( "Unable to attach to port!"); System.exit(1); } do{ handle(); }while(true); } private static void handle(){ Socket link= null; System.out.println("waiting for a client ..."); try{ link= server.accept(); System.out.println("client accepted."); Scanner input=new Scanner(link.getInputStream()); PrintWriter output= new PrintWriter(link.getOutputStream(),true); String message=null; output.println("i found you"); System.out.println("waiting for client response ..."); message = input.nextLine(); System.out.println("message recived"); while(!message.equals("CLS") ){ System.out.println("client> "+ message); output.println("your message recived :"+message); message=input.nextLine(); } } catch(IOException ioEx) { ioEx.printStackTrace(); } finally { try { System.out.println( "\n* Closing connection… *"); link.close(); //Step 5. } catch(IOException ioEx) { System.out.println( "Unable to disconnect!"); System.exit(1); } } } }
import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class SimpleClient { private static InetAddress host; private static int port = 3234; public static void main(String[] args) { // TODO Auto-generated method stub try { host = InetAddress.getLocalHost(); } catch(UnknownHostException uhEx) { System.out.println("Host ID not found!"); System.exit(1); } Socket link=null; try{ link=new Socket(host,port); Scanner input=new Scanner(link.getInputStream()); Scanner userInput=new Scanner(System.in); PrintWriter output=new PrintWriter(link.getOutputStream()); String message=null,clientMessage=null; output.println("hi server"); do{ System.out.print("Enter message: "); clientMessage=userInput.nextLine(); System.out.println("client> "+clientMessage); output.println(clientMessage); System.out.println("Waiting for server ...."); message=input.nextLine(); System.out.println("server> "+message); }while(!message.equals("CLS")); } catch(IOException io){ System.out.println("server not founded"); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)