Advertisement
Shailrshah

Concurrent TCP Client-Server

Apr 24th, 2015
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. //Server.java
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.io.*;
  5. class Server implements Runnable{
  6.     static ServerSocket ss;
  7.     Socket s;
  8.     public void run(){
  9.         try{
  10.             BufferedReader fromClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
  11.             PrintStream toClient = new PrintStream(s.getOutputStream());
  12.  
  13.             String ip = "";
  14.             while((ip=fromClient.readLine())!=null){
  15.                 System.out.println(ip);
  16.                 toClient.println(ip.toUpperCase());
  17.                 if(ip.equals("bye")) break;
  18.             }
  19.         } catch(Exception e){e.printStackTrace();}
  20.     }
  21.     Server(Socket s){
  22.         this.s = s;
  23.     }
  24.     public static void main(String[] args) throws IOException{
  25.         ss = new ServerSocket(9812);
  26.         while(true){
  27.             new Thread(new Server(ss.accept())).start();
  28.         }
  29.     }
  30. }
  31.  
  32. //Client.java
  33. import java.net.Socket;
  34. import java.io.*;
  35. class Client{
  36.     public static void main(String[] args){
  37.         try{
  38.             Socket s = new Socket("localhost", 9812);
  39.             BufferedReader fromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
  40.             PrintStream toServer = new PrintStream(s.getOutputStream());
  41.  
  42.             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  43.             System.out.println("Enter a string to capitalize.");
  44.             String ip;
  45.             while(!(ip=br.readLine()).equals("bye")){
  46.                 toServer.println(ip);
  47.                 System.out.println(fromServer.readLine());
  48.             }
  49.             s.close();
  50.         } catch(Exception e){e.printStackTrace();}
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement