Advertisement
bokunda

Soketi

May 31st, 2020
1,229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.41 KB | None | 0 0
  1. //////////// Datagram sockets
  2.  
  3. public class Server {
  4.         public static void main(String []args){
  5.             try{
  6.                 byte[] buffer = new byte[256];
  7.                 DatagramSocket socket = new DatagramSocket(1234);
  8.                 DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
  9.                 System.out.println("Listening for packets...");
  10.                 socket.receive(packet);
  11.                 System.out.println("Packet recieved! it contains: ");
  12.                 for(byte b: packet.getData()){
  13.                     System.out.print((char) b);
  14.                 }
  15.             }catch(IOException e){
  16.                 System.err.println(e.getMessage());
  17.             }
  18.         }
  19. }
  20.  
  21. public class Client {
  22.     public static void main(String []args){
  23.         try{
  24.             System.out.println("Connecting to server...");
  25.             Socket socket = new Socket(InetAddress.getByName("localhost"), 1234);
  26.  
  27.             System.out.println("Connected to server! Writing \"Hello!\" to socket's output stream...");
  28.             // "hello".getBytes()
  29.             socket.getOutputStream().write(new byte[]{'h','e','l','l','o','!'});
  30.            
  31.             System.out.println("Wrote to the stream! Closing...");
  32.             socket.close();
  33.            
  34.             System.out.println("Closed! Goodbye :) ");
  35.         }catch(IOException e){
  36.             System.err.print(e.getMessage());
  37.         }
  38.     }
  39. }
  40.  
  41. //////////// Stream sockets
  42.  
  43. public class Server {
  44.     public static void main(String []args){
  45.         try{
  46.             System.out.println("Creating server socket at port 1234...");
  47.             ServerSocket serverSocket = new ServerSocket(1234);
  48.           //  System.out.println("Acceptiong client...");
  49.             Socket socket = serverSocket.accept();
  50.           //  System.out.println("Client accepted, wating 5 seconds for buffer...");
  51.             byte [] buffer = new byte[256];
  52.             Thread.sleep(5000);
  53.            
  54.          //   System.out.println("Reading buffer...");
  55.             socket.getInputStream().read(buffer);
  56.             for(byte b: buffer){
  57.                     System.out.print((char) b);
  58.             }
  59.             System.out.println("That is all, closing socket...");
  60.             socket.close();
  61.          //   System.out.println("Aufviedersehn!");
  62.         }catch(IOException e){
  63.             System.err.print(e.getMessage());
  64.         }catch(InterruptedException e){
  65.             System.err.print(e.getMessage());
  66.         }
  67.     }
  68. }
  69.  
  70. public class Client {
  71.     public static void main(String []args){
  72.         try{
  73.             System.out.println("Connecting to server...");
  74.             Socket socket = new Socket(InetAddress.getByName("localhost"), 1234);
  75.  
  76.             System.out.println("Connected to server! Writing \"Hello!\" to socket's output stream...");
  77.             // "hello".getBytes()
  78.             socket.getOutputStream().write(new byte[]{'h','e','l','l','o','!'});
  79.            
  80.             System.out.println("Wrote to the stream! Closing...");
  81.             socket.close();
  82.            
  83.             System.out.println("Closed! Goodbye :) ");
  84.         }catch(IOException e){
  85.             System.err.print(e.getMessage());
  86.         }
  87.     }
  88. }
  89.  
  90. //////////// NIO
  91.  
  92. public class Client {
  93.  
  94.     public static void main(String[] args) throws IOException {
  95.         SocketAddress address = new InetSocketAddress(InetAddress.getByName("localhost"), 9090);
  96.         SocketChannel channel = SocketChannel.open(address);
  97.        
  98.         Thread nit = new Thread(new Runnable() {
  99.            
  100.             @Override
  101.             public void run() {
  102.                 ByteBuffer podaciSaServera = ByteBuffer.allocate(256);
  103.                 podaciSaServera.clear();
  104.                
  105.                 while (true) {
  106.                     try {
  107.                         channel.read(podaciSaServera);
  108.                         podaciSaServera.flip();
  109.                         System.out.println();
  110.                         while (podaciSaServera.hasRemaining()) {
  111.                             System.out.print((char)podaciSaServera.get());
  112.                         }
  113.                         System.out.println();
  114.                         podaciSaServera.clear();
  115.                     } catch (IOException e) {
  116.                         // TODO Auto-generated catch block
  117.                         e.printStackTrace();
  118.                     }                  
  119.                 }              
  120.             }
  121.         });
  122.        
  123.         nit.start();
  124.  
  125.         /// slanje na server
  126.         Scanner scanner = new Scanner(System.in);
  127.         ByteBuffer buffer = ByteBuffer.allocate(256);
  128.         while(true)
  129.         {
  130.             String line = scanner.nextLine();
  131.             buffer.put(line.getBytes());
  132.             buffer.flip();
  133.             channel.write(buffer);
  134.             buffer.clear();
  135.         }
  136.     }
  137. }
  138.  
  139. public class Server {
  140.  
  141.     static int port = 9090;
  142.     static ServerSocketChannel ssc = null;
  143.     static Selector selector = null;
  144.     public static void main(String[] args) throws IOException {
  145.        
  146.         ssc = ServerSocketChannel.open();
  147.         ServerSocket socket = ssc.socket();
  148.         InetSocketAddress isa = new InetSocketAddress(port);
  149.         socket.bind(isa);
  150.        
  151.         ssc.configureBlocking(false); // vazno
  152.         selector = Selector.open();
  153.         ssc.register(selector, SelectionKey.OP_ACCEPT);
  154.         System.out.println("Server is started at port: "+ port);
  155.  
  156.         while(true)
  157.         {
  158.             selector.select();
  159.             Set<SelectionKey> selectionKeys = selector.selectedKeys();
  160.             Iterator<SelectionKey> kljucevi = selectionKeys.iterator();
  161.            
  162.             while (kljucevi.hasNext()) {
  163.                 SelectionKey selectionKey = (SelectionKey) kljucevi.next();
  164.                 kljucevi.remove();
  165.                 if(selectionKey.isAcceptable())
  166.                 {
  167.                     ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
  168.                     SocketChannel klijentskiKanal = serverSocketChannel.accept();
  169.                     klijentskiKanal.configureBlocking(false);
  170.                     String ip_adresa = klijentskiKanal.socket().getInetAddress()
  171.                                         + ":" + klijentskiKanal.socket().getPort();
  172.                    
  173.                     klijentskiKanal.register(selector, SelectionKey.OP_READ, ip_adresa);
  174.                 }
  175.                 else if (selectionKey.isReadable())
  176.                 {
  177.                     SocketChannel klijent = (SocketChannel) selectionKey.channel();
  178.                     ByteBuffer buffer = ByteBuffer.allocate(256);
  179.                     buffer.clear();
  180.                    
  181.                     // citanje iz kanala
  182.                     klijent.read(buffer);
  183.                     buffer.flip();
  184.                    
  185.                     String poruka = selectionKey.attachment() + " ";
  186.                     while (buffer.hasRemaining()) {
  187.                         poruka += (char)buffer.get();
  188.                     }
  189.                     posaljiSvima(poruka);
  190.                 }              
  191.             }
  192.         }      
  193.     }
  194.    
  195.     private static void posaljiSvima(String poruka) throws IOException
  196.     {
  197.         ByteBuffer buffer = ByteBuffer.wrap(poruka.getBytes());
  198.        
  199.         for(SelectionKey kljuc: selector.keys())
  200.         {
  201.             if(kljuc.isValid() && kljuc.channel() instanceof SocketChannel)
  202.             {
  203.                 SocketChannel klijent = (SocketChannel)kljuc.channel();
  204.                 klijent.write(buffer);
  205.                 buffer.rewind();
  206.             }
  207.         }
  208.     }
  209. }
  210.  
  211. //////////// RMI
  212. public class Klijent
  213. {
  214.     public static void main(String[] args)
  215.     {
  216.         try
  217.         {  
  218.             System.out.println("Konektovanje na server....");
  219.              
  220.             BrojacI server = (BrojacI)Naming.lookup("rmi://localhost/Server");
  221.              
  222.             System.out.println("Brojac: " + server.count());
  223.              
  224.         }
  225.         catch (Exception ex)
  226.         {
  227.             ex.printStackTrace();
  228.         }
  229.     }
  230. }
  231.  
  232. public class Server
  233. {
  234.       public static void main(String[] args)
  235.       {
  236.           try
  237.           {  
  238.               Brojac brojac = new Brojac();
  239.               LocateRegistry.createRegistry(1099);
  240.               Naming.rebind("//localhost:1099/Server", brojac);
  241.              
  242.               System.out.println("Server je startovan.");
  243.              
  244.           }
  245.           catch (Exception ex)
  246.           {
  247.               ex.printStackTrace();
  248.           }
  249.       }
  250. }
  251.  
  252. public class Brojac extends UnicastRemoteObject implements BrojacI
  253. {  
  254.     private static final long serialVersionUID = -117253489961899775L; 
  255.     private int count = 0;
  256.  
  257.     public Brojac() throws RemoteException
  258.     {  
  259.     }
  260.    
  261.     public int count() throws RemoteException
  262.     {
  263.         return ++count;
  264.     }
  265. }
  266.  
  267. public interface BrojacI extends Remote
  268. {
  269.     public int count() throws RemoteException;
  270. }
  271.  
  272. //////////// Multicast UDP
  273. public class Server {
  274.     public static void main(String[] args) {
  275.         int socketPort = Common.SOCKET_PORT;
  276.         try {
  277.             InetAddress adress = InetAddress.getByName(Common.ADDRESS); // group
  278.             MulticastSocket socket = new MulticastSocket(socketPort);
  279.             socket.setTimeToLive(1);
  280.             socket.joinGroup(adress);
  281.  
  282.             while (true) {
  283.                 String poruka = "Pozdrav svima";
  284.                 byte[] data = poruka.getBytes();
  285.                 DatagramPacket packet = new DatagramPacket(data, data.length, adress, socketPort);
  286.                 socket.send(packet);
  287.                 System.out.println("Poslao podatke");
  288.                 Thread.sleep(5000);
  289.             }
  290.         } catch (IOException e) {
  291.             //TODO: handle exception
  292.         }catch (Exception e) {
  293.             //TODO: handle exception
  294.         }
  295.     }
  296. }
  297.  
  298. public class Client {
  299.     public static void main(String[] args) {
  300.         int socketPort = Common.SOCKET_PORT;
  301.         try {
  302.             InetAddress address = InetAddress.getByName(Common.ADDRESS);
  303.             MulticastSocket socket = new MulticastSocket(socketPort);
  304.             socket.joinGroup(address);
  305.             byte[] data = new byte[1024];
  306.             while (true) {
  307.                 DatagramPacket dp = new DatagramPacket(data, data.length, address, socketPort);
  308.                 socket.receive(dp);
  309.                 String poruka = new String(dp.getData());
  310.                 System.out.println(poruka.trim());                
  311.             }
  312.        
  313.         } catch (Exception e) {
  314.             //TODO: handle exception
  315.         }
  316.     }
  317. }
  318.  
  319. public class Common {
  320.     public static int SOCKET_PORT = 5776;
  321.     public static String ADDRESS = "228.5.6.7";
  322. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement