Navigacija
Lista poslednjih: 16, 32, 64, 128 poruka.

Socket programiranje Hitno

[es] :: Java :: Socket programiranje Hitno

[ Pregleda: 2175 | Odgovora: 4 ] > FB > Twit

Postavi temu Odgovori

Autor

Pretraga teme: Traži
Markiranje Štampanje RSS

Filipp

Član broj: 58401
Poruke: 13
*.unitymediagroup.de.



Profil

icon Socket programiranje Hitno24.11.2009. u 14:55 - pre 175 meseci
Dakle za faks imam zadatak da napisem Socket aplikaciju (Klient i Server) gde Server kontinuirano radi , tj. moze vise
zahteva jedan za drugim da obradi.

Sa Klijenta dajemo komandu pruzmi<ime fajla>. Server treba da potrazi fajl u svom lokalnom direktorijumu i
da posalje sadrzaj fajla klijentu tj. ispise sadrzaj na ekranu. U pitanju je jednostavan .txt fajl.
Sa komandom Stop klijent signalizira serveru tj. server prestaje sa radom.

Code:

import java.net.*;
import java.io.*;
public class SimpleServer {
  public static void main(String args[]) throws IOException {
    // Register service on port 1234
    ServerSocket s = new ServerSocket(1234);
    Socket s1=s.accept(); // Wait and accept a connection
    // Get a communication stream associated with the socket
    OutputStream s1out = s1.getOutputStream();
    DataOutputStream dos = new DataOutputStream (s1out);
    // Send a string!
    dos.writeUTF("Hi there");
    // Close the connection, but not the server socket
    dos.close();
    s1out.close();
    s1.close();
  }
}


i klijent

Code:


import java.net.*;
import java.io.*;
public class SimpleClient {
  public static void main(String args[]) throws IOException {
    // Open your connection to a server, at port 1234
    Socket s1 = new Socket("localhost",1234);
    // Get an input file handle from the socket and read the input
    InputStream s1In = s1.getInputStream();
    DataInputStream dis = new DataInputStream(s1In);
    String st = new String (dis.readUTF());
    System.out.println(st);
    // When done, just close the connection and exit
    dis.close();
    s1In.close();
    s1.close();
  }
}


E sada imam i gotovu klasu ReadFromFile ali mi nije jasno kako da povezem tj. promenim klase Client i Server da
dobijem zeljeni rezultat.
Svaka pomoc dobrodosla!

Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class ReadFromFile {

   
    public static void main(String[] args) {
        ReadFromFile rff=new ReadFromFile();
        rff.readFile();
        
    }
    
    public void readFile()
    {

        File file = new File ("input.txt");

        Scanner scanner = null;
        try {
   
           scanner = new Scanner (file);
        } catch (FileNotFoundException e) {
          System.out.println ("File not found!");
         
          System.exit (0);
        }
   
        while(scanner.hasNext())
        {

            String tmp=scanner.nextLine();

            System.out.println(tmp);
        }
        
    }

}





 
Odgovor na temu

nnn
Tech Lead
Haxr.io
Beograd

Član broj: 16743
Poruke: 679
79.101.203.*



+87 Profil

icon Re: Socket programiranje Hitno27.11.2009. u 23:25 - pre 175 meseci
Odgovorio sam ti na drugom forumu gde si postavio istu temu, al reko ajd i ovde, mozda nekom drugom zatreba..
Posto se nisam do sada bavio java i socketima, a i imao sam par sati slobodnog vremena odradio sam ti program ceo za vezbu sebi i iztestirao ga. Bice ti potrebno paket usluge.Citaj od gospodina Lasla krausa( mrzelo me je da pisem citanje sa konzole iskreno) :P
[url]http://kondor.etf.rs/~kraus/knjige/programi/rzj2.zip[/url]
u zip fajlu imas Folder Usluge, samo ga prevuci u svoj projekat u eclipse..

E ovako evo ti kod,

Server:

Klasa ReadFromFile

Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFromFile {
    File file;
    Scanner scanner;
    public ReadFromFile(String f)
    {
        file = new File (f);
        try {
               System.out.println("Trying to read file: "+f);
               scanner = new Scanner (file);
            } catch (FileNotFoundException e) {
              System.out.println ("File not found!");
             System.exit (0);
            }
    }
    public Scanner GetScanner(){return scanner;}

}




Klasa Sserver

Code:

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

import java.util.Scanner;
public class Sserver {
    ServerSocket s;
    Socket s1;
    OutputStream s1out;
    DataInputStream streamIn;
    DataOutputStream dos;
    public Sserver(int port){
        try {
            System.out.println("Binding to port " + port + ", please wait  ...");
            s=new ServerSocket(port);
            System.out.println("Server started: " + s);
             System.out.println("Waiting for a client ..."); 
             s1 = s.accept();
             System.out.println("Client accepted: " + s1);
             dos = new DataOutputStream(s1.getOutputStream());
             open();
             Boolean stop= false;
             String line=null;
             while(!stop){
                 open();
                 try
                        {  
                          line = streamIn.readUTF();
                          System.out.println("File name receved:"+ line);
                          stop = line.equals(".stop"); //sve dok mu ne posaljes .stop server ce raditi..
                        }
                      catch(IOException ioe)
                        {  
                          stop = true;
                        close();
                        }
                      
             if(!stop){
                ReadFromFile MyFile=new ReadFromFile(line); 
                Scanner scn=MyFile.GetScanner();
                 
               while(scn.hasNext())
             {
                   String temp=scn.nextLine();
                    dos.writeUTF(temp);
                 }
                 dos.writeUTF(".eof");
             }
             
             }
             } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    
    public void open() throws IOException
       {  streamIn = new DataInputStream(new BufferedInputStream(s1.getInputStream()));
       }
     public void close() throws IOException
       {  if (s1 != null)    s1.close();
          if (streamIn != null)  streamIn.close();
         }
    }


Klasa main za server
Code:

public class Main {

    public static void main(String[] args) {
System.out.println("Welcome to server");
Sserver server1= new Sserver(1225);//1225 port koji osluskuje
}
}



E sad klient:

Klasa Sclient:
Code:

import java.net.*;
import java.io.*;
public class Sclient {

    Socket s1;
    InputStream s1In;
    OutputStream s1Ou;
    DataInputStream dis;
    DataOutputStream dos;
    
    public Sclient(String host, int port)
    {
        System.out.println("Establishing connection. Please wait ...");
        try{
        s1 = new Socket(host,port);
        System.out.println("Connected to "+host+":"+port);
        
         s1In = s1.getInputStream();
         s1Ou = s1.getOutputStream();
         dis = new DataInputStream(s1In);
         dos = new DataOutputStream(s1Ou);
        }catch(UnknownHostException uhe)
        {  System.out.println("Host unknown: " + uhe.getMessage());}
        catch(IOException ioe)
        {System.out.println("Unexpected exception: " + ioe.getMessage());}
    }
    
    public void SendReq(String fname)//Funkcija koja salje ime fajla serveru
    {
        try {
            dos.writeUTF(fname);
        } catch (IOException e) {
            System.out.println("Error sending request: "+ e.getMessage());
            e.printStackTrace();
        }
    }
    public void ReadFile(){ //Funckija koja prima fajl od servera
        try {
            Boolean eof = false;
            while(!eof){  //Gledamo dal smo stigli do kraja fajla
            String line=dis.readUTF();
            eof = line.equals(".eof");
            if(!eof){System.out.println(line);} //Ako nismo primili .eof za kraj odstampaj linuju
            else {System.out.println("End of file");}

            }
        } catch (IOException e) {
            System.out.println("Error receving file: "+ e.getMessage());
            e.printStackTrace();
        }
    }
}
    



i klasa main za klient:
Code:
import usluge.Citaj;
public class Main {

    public static void main(String[] args) {
        
        System.out.println("Welcome, enter server address, and port");
        String server= Citaj.String();//citamo server i port
        int port =Citaj.Int();        // sa glavnog ulaza
        Sclient client = new Sclient(server,port); //pravimo objekat klase Sclient
        while(true){     //Vrtimo se sve dok ne izdamo narednu .exit
        System.out.println("Enter file name or path on server or .exit to exit");
        String file=Citaj.String();
        if(file.equals(".exit"))System.exit(1);
        client.SendReq(file);//saljemo request za file
        client.ReadFile();  // Primamo file i ispisujemo
        }
    }

}


Evo nadam se da je sve jasno.. Koristio sam engleski za poruke, posto tako volim jbg.. :P Kod moze mnogo da se ulepsa ali nisam imao vremena za to..
 
Odgovor na temu

staticInt

Član broj: 66101
Poruke: 485
91.150.106.*



+43 Profil

icon Re: Socket programiranje Hitno28.11.2009. u 00:39 - pre 175 meseci
Mozda bi bilo pametno da mu ubacis i multi threading, da svaki client ide u posebnom threadu.
 
Odgovor na temu

nnn
Tech Lead
Haxr.io
Beograd

Član broj: 16743
Poruke: 679
79.101.203.*



+87 Profil

icon Re: Socket programiranje Hitno28.11.2009. u 01:24 - pre 175 meseci
Nema potrebe sto se tice zadatka..
 
Odgovor na temu

TheNatural
Slaviša Perišić
student
Beograd

Član broj: 177690
Poruke: 7
212.200.212.*

Sajt: iwalkedaway.wordpress.com


Profil

icon Re: Socket programiranje Hitno22.12.2009. u 13:25 - pre 174 meseci
Citat:
staticInt: Mozda bi bilo pametno da mu ubacis i multi threading, da svaki client ide u posebnom threadu.


E ovo bih voleo da neko uradi ako nije problem, puno bi mi znacilo da vidim da li sam ispratio niti kako treba :)
my computer can represent 0.1 anytime, binary!!! :)
 
Odgovor na temu

[es] :: Java :: Socket programiranje Hitno

[ Pregleda: 2175 | Odgovora: 4 ] > FB > Twit

Postavi temu Odgovori

Navigacija
Lista poslednjih: 16, 32, 64, 128 poruka.