Advertisement
fak123

PWSI Z1 zajecia4 Serwer

May 30th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. package zad_ii_1;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.util.*;
  6. public class Serwer
  7. {
  8. public static final int serverPort = 2020;
  9. ServerSocket s;
  10.     /* Konstruktor próbuje utworzyć gniazdo */
  11.     Serwer()
  12.     {
  13.         try{
  14.             s = new ServerSocket(serverPort);
  15.             System.out.println("Serwer dziala");
  16.         }catch(Exception e) {
  17.             System.out.println("Nie można utworzyć gniazda");
  18.             System.exit(1);
  19.         }
  20.     }
  21.     void uruchom() throws Exception
  22.     {
  23.         /* Czekaj, aż klient się połączy */
  24.         Socket socket = s.accept();
  25.         /* Czynności przygotowawcze do obsługi klienta */
  26.         /* 1. Otworzenie strumienia (wejściowego lub wyjściowego) i
  27.         /* skojarzenie go z gniazdem klienta */
  28.        
  29.         Scanner in = new Scanner(System.in);
  30.        
  31.         PrintWriter out = new PrintWriter(
  32.                 new OutputStreamWriter(
  33.                         socket.getOutputStream()), true);
  34.         String komunikat;
  35.         while(true)
  36.         {
  37.             komunikat = in.nextLine();
  38.             if(komunikat.equalsIgnoreCase("q"))
  39.             {
  40.                 System.out.println("Koniec pracy serwera");
  41.                 socket.close();
  42.                 s.close();
  43.                 return;
  44.             }
  45.     else
  46.     {
  47.         try
  48.         {
  49.         /* Wyślij/Odbierz dane do/od klienta */
  50.         /* (do/ze strumienia związanego z gniazdem) */
  51.             out.println(komunikat);
  52.         }catch(Exception e) {
  53.             System.out.println("Brak klienta - koncze prace");
  54.             socket.close();
  55.             return;
  56.             }
  57.         }
  58.     }//koniec pętli while(true)
  59. }//koniec funkcji uruchom()
  60.  
  61.     public static void main(String args[]) throws Exception
  62.     {
  63.         Serwer server = new Serwer();
  64.         server.uruchom();
  65.         server.s.close();
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement