Anonymní profil m – Programujte.com
 x   TIP: Přetáhni ikonu na hlavní panel pro připnutí webu

Anonymní profil m – Programujte.comAnonymní profil m – Programujte.com

 

Příspěvky odeslané z IP adresy 93.89.146.–

MySQL › PROCEDURA: pokud je nove vkl…
4. 4. 2016   #209615

#6 Kit
Mam to na logovani uptime zarizeni. Pokud zarizeni bezi, posila svuj uptime, ktery se zvetsuje. Je to pocet sekund od zapnuti.

Po restartu je cislo mensi, takze potrebuji vytvorit novy zaznam.

Jak uz jsem psal, v tabulce chybi par sloupcu.

MySQL › PROCEDURA: pokud je nove vkl…
4. 4. 2016   #209613

#4 KIIV
Uplne stejne, pred vkladanim jsem spustil: 

DROP TABLE IF EXISTS test;
CREATE TABLE test (...

DELIMITER $$
DROP PROCEDURE IF EXISTS p_insert_new_uptime $$
CREATE PROCEDURE p_insert_new_uptime (...

Mel bych to nejak osetrit?

MySQL › PROCEDURA: pokud je nove vkl…
4. 4. 2016   #209611

#2 KIIV
Nevyteckoval, phpmyadmin mi je useknul a dal tri tecky.

Ted jsem zkusil terminaloveho mysql klienta a vse funguje vyborne: 

mysql> CALL p_insert_new_uptime(UNIX_TIMESTAMP());
+----------------------------------------------------------+
| INFO                                                     |
+----------------------------------------------------------+
| UPDATE: [old_uptime=1459771579], [new_uptime=1459771585] |
+----------------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.01 sec)

mysql> CALL p_insert_new_uptime(UNIX_TIMESTAMP());
+----------------------------------------------------------+
| INFO                                                     |
+----------------------------------------------------------+
| UPDATE: [old_uptime=1459771585], [new_uptime=1459771590] |
+----------------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.00 sec)

mysql> CALL p_insert_new_uptime(123);
+---------------------------------------------------+
| INFO                                              |
+---------------------------------------------------+
| INSERT: [old_uptime=1459771590], [new_uptime=123] |
+---------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.01 sec)

mysql> CALL p_insert_new_uptime(UNIX_TIMESTAMP());
+---------------------------------------------------+
| INFO                                              |
+---------------------------------------------------+
| UPDATE: [old_uptime=123], [new_uptime=1459771606] |
+---------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.02 sec)

mysql> CALL p_insert_new_uptime(147);
+---------------------------------------------------+
| INFO                                              |
+---------------------------------------------------+
| INSERT: [old_uptime=1459771606], [new_uptime=147] |
+---------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.00 sec)

mysql> CALL p_insert_new_uptime(148);
+--------------------------------------------+
| INFO                                       |
+--------------------------------------------+
| UPDATE: [old_uptime=147], [new_uptime=148] |
+--------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.01 sec)

mysql> CALL p_insert_new_uptime(UNIX_TIMESTAMP());
+---------------------------------------------------+
| INFO                                              |
+---------------------------------------------------+
| UPDATE: [old_uptime=148], [new_uptime=1459771633] |
+---------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 1 row affected (0.02 sec)

mysql> 

Mohlo za to spatne zobrazeni v phpmyadminu asi. Prikazy jsem volal 100% stejne.

Omlouvam se za zbytecny dotaz, priste zkusim rovnou textoveho klienta.

Kdyz uz jsem dotaz vytvoril, muzete se nekdo prosim podivat na moji proceduru? Je takhle v poradku, nebo delam neco spatne/nevhodne? (Jeste pridam sloupec timestampu, ktery se zavola pouze pri insertu.)

MySQL › PROCEDURA: pokud je nove vkl…
4. 4. 2016   #209607

Ahoj, rad bych si napsal proceduru, na vkladani aktualizaci uptime.

Pokud je vkladany cas novejsi, nez prechozi udela update posledniho zaznamu. Pokud je starsi, vytvori novy zaznam. Mam to na logovani uptime. Zatim bych rad pro info vypsal po zavolani procedury informaci.

DROP TABLE IF EXISTS test;
CREATE TABLE test (
  id int(11) NOT NULL AUTO_INCREMENT,
  uptime bigint NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;



DELIMITER $$

DROP PROCEDURE IF EXISTS p_insert_new_uptime $$
CREATE PROCEDURE p_insert_new_uptime (
	IN new_uptime LONG
	)
COMMENT 'Pokud je nove vkladane cislo vetsi, nez minule, misto INSERT udela UPDATE.'
BEGIN
	SELECT id, uptime INTO @old_id, @old_uptime
	FROM test
	ORDER BY id DESC
	LIMIT 1;
	
	IF @old_uptime <= new_uptime THEN
		SELECT CONCAT("UPDATE: [old_uptime=", CAST(@old_uptime AS CHAR), "], [new_uptime=", CAST(new_uptime AS CHAR), "]") AS INFO;
		UPDATE test SET uptime=new_uptime WHERE id=@old_id;
	ELSE
		SELECT CONCAT("INSERT: [old_uptime=", CAST(@old_uptime AS CHAR), "], [new_uptime=", CAST(new_uptime AS CHAR), "]") AS INFO;
		INSERT INTO test (uptime) VALUES (new_uptime);
	END IF;
END$$

Kdyz zavolam:

CALL p_insert_new_uptime(UNIX_TIMESTAMP());

vypise se: 

UPDATE: [old_uptime=1459769615], [new_uptime=14597...

pokud ho volam treba po 10s znova, prepise puvodni radek, coz je spravne. Jenze i uplne prvni vlozeni do prazdne tabulky vypise UPDATE: [...

Pokud zavolam: 

CALL p_insert_new_uptime(123);

vlozi se novy radek, ale stale se vypise UPDATE: [...

Muzete mi prosim poradit, co delam spatne?

Pouzivam MySQL 5.5.47 na Debianu 8.

MySQL › BLOB - ukladat soubory v DB,…
1. 11. 2013   #183069

Ahoj,

mam priblizne takovouto tabulku:

https://db.tt/0iu0dfxOPřipojen obrázek.

a resim problem jak ukladat fotku uzivatele. Rozliseni odhaduji asi na 100x100px a velikost 20-50kB. Me se zda nejlepsi ukladat fotky na disk a pojmenovat je napr. podle ID z tabulky. Par lidi me ale presvedcuje, ze je lepsi BLOB v databazi. Ja jsem BLOB nikdy na nic nepouzival, tudiz s nim nemam vubec zadne zkusenosti.

Pro 10 zaznamu je to jedno, ale kdyz budu mit v tabulce treba 5 nebo 50 milionu uzivatelu a kazdy bude mit 50kB fotku, jaky bude vykon ve srovnani se soubory?

Me se vic libi reseni se soubory na disku, ale rad se necham poucit.

Pri vysokem provozu muze staticke fotky posilat webserver (nginx pred apachem) a nemusi bezet proces PHP s otevrenym spojenim do DB. Fotky taky muzou byt snadno rozlozeny na vice serverech. U DB je zase vse resene "jednim zpusobem" - k intum, varcharum i binarnim datum se pristupuje stejne.

Kdyby fotky meli treba 3MB, mela by DB jeste vyznam?

Nasel jsem stary clanek z roku 2004, kde BLOB kritizuji. Ale za 9 let se urcite dost zmenilo...

Připojen obrázek.

U DB bude urcite snadny prenos na jiny server. Zadne cesty k souborum. Mozna je v DB lepe resene hledani fotky, nez u souboroveho systemu na disku. Souborovy system ma take limit souboru v jednom adresari.

Co je podle vas lepsi a proc?

martin
Java › Navrh app na kresleni logick…
5. 9. 2013   #181070

Ahoj,

rad bych si zkusil udelat jednoduchou app na navrh logickych funkci. Moje predstava je asi nasledujici:

Vlevo sloupec 4 vstupu - volne misto - vpravo sloupec 4 vystupu (pocty klidne jine, 4 davam jako priklad).

Uzivatel by napriklad chtel vytvorit kontrukci "if ((vstup1 and vstup2) or vstup4) then vystup3". A tu ja potrebuju take vygenerovat jako vystup.

Napadlo me pouzit comboboxy kterymi by uzivatel vybral pozadovanou funkci. Jeste by se nejak muselo vyresit popropojovani mezi sebou.

Připojen obrázek.Ale to je asi blbost. Pak me napadlo pouzit Gprahics2D a BufferedImage a vkladat na platno symboly logickych funkci a udelat si uchopove body kterymi by mohl uzivatel jednotlive vstupy/vystupy propojovat. Da to mnohem vic prace, ale prijde mi to lepsi. Da se nejak resit pri propojeni symbolu aby se cara sama zalamovala a nesla "vzdusnou carou", nebo si to musim napsat sam?

Porad ale bude problem s pretahovanim symbolu - cele to napsat by bylo hodne pracne.

Poradte mi prosim, ktery zpusob se vam zda lepsi a jestli vas pripadne nenapadne nejake uplne jine, lepsi reseni.

Libi se mi:

http://320volt.com/wp-content/uploads/2009/01/buton-kontaktorlerin-plc-baglantisi-2.png

http://plccompare.com/wp-content/uploads/2011/02/WindLGC.png

Diky za vase pripominky.

martin1
Java › JEE6 tutorial ..CZ?
5. 9. 2013   #181067

Rad bych se take podle nejake knihy naucil Javu EE. Konkretne mi jde o tvorbu webu v Jave.

Nasel jsem knihu Beginning EJB 3, ktera uz by mela byt psana na Javu EE 7.

Myslite si, ze je te kniha dobra, nebo je lepsi neco jako The Java EE 6 Tutorial?

V Jave jsem zatim napsal jenom par jednodussich swing aplikaci a trochu jsem se ucil webovy Stripes framework.

martin
Java › Stripes a Spring jak na SQL…
28. 8. 2013   #180863

Ahoj, snazim se podle navodu Stripes a Spring ve webových aplikacích udelat jednoduchy adresar (ucim se, vim ze je adresar k nicemu).

Mam zatim nasledujici db v MySQL:

Připojen obrázek.

Pro tabulku stat mam upraveny kod podle vyse uvedeneho tutorialu (funguje):

package com.example.test.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper;
import org.springframework.stereotype.Repository;

@Repository("statManager")
public class StatManagerImpl implements StatManager {
    
    final static Logger log = LoggerFactory.getLogger(StatManagerImpl.class);

    public StatManagerImpl() {
        log.debug("vytvoren");
    }
    
    private JdbcTemplate jdbc;
    
    @Autowired
    public void setDataSource(DataSource dataSource) {
        log.debug("dataSource set to {}", dataSource);
        jdbc = new JdbcTemplate(dataSource);
    }
    
    private static final RowMapper<Stat> STAT_MAPPER = new RowMapper<Stat>() {
        @Override
        public Stat mapRow(ResultSet rs, int i) throws SQLException {
            Stat stat = new Stat();
            stat.setId(rs.getInt("id"));
            stat.setNazev(rs.getString("nazev"));
            return stat;
        }
    };
    
    private static final ParameterizedSingleColumnRowMapper<String> STRING_MAPPER = ParameterizedSingleColumnRowMapper.newInstance(String.class);

    @Override
    public void vytvoritStat(Stat stat) {
        jdbc.update("INSERT INTO stat (nazev) VALUES (?)", stat.getNazev() );
    }

    @Override
    public Stat getStatById(int id) {
        return jdbc.queryForObject("SELECT * FROM stat WHERE id = ?", STAT_MAPPER, id);
    }
    
    @Override
    public Stat getStatByNazev(String nazev) {
        return jdbc.queryForObject("SELECT * FROM stat WHERE nazev = ?", STAT_MAPPER, nazev);
    }

    @Override
    public List<Stat> getVsechnyStaty() {
        return jdbc.query("SELECT id, nazev FROM stat ORDER BY nazev", STAT_MAPPER);
    }

    @Override
    public void aktualizaceStatu(Stat stat) {
        jdbc.update("UPDATE stat SET nazev=? WHERE id=?", stat.getNazev(), stat.getId() );
    }

    @Override
    public void smazaniStatu(Stat stat) {
        jdbc.update("DELETE FROM stat WHERE id = ?", stat.getId() );
    }     
    
}

/* -------------------------------------------------------------- */
package com.example.test.web;

import com.example.test.model.Stat;
import com.example.test.model.StatManager;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@UrlBinding("/staty/{$event}/{stat.id}")
public class StatActionBean implements ActionBean {

    final static Logger log = LoggerFactory.getLogger(StatActionBean.class);

    private ActionBeanContext context;
    
    @SpringBean
    protected StatManager statManager;    
    
    @DefaultHandler
    public Resolution all() {
        log.debug("all()");
        return new ForwardResolution("/statyShow.jsp");
    }
    
    public List<Stat> getStaty() {
        return statManager.getVsechnyStaty();
    }  

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }
    
    @ValidateNestedProperties(value = {
            @Validate(on = {"add", "save"}, field = "nazev", required = true, minlength = 3)
    })
    private Stat stat;

    public Stat getStat() {
        return stat;
    }

    public void setStat(Stat stat) {
        this.stat = stat;
    }
    
    public Resolution add() {
        log.debug("add() stat={}", stat);
        statManager.vytvoritStat(stat);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution delete() {
        log.debug("delete({})", stat.getId());
        statManager.smazaniStatu(stat);
        return new RedirectResolution(this.getClass(), "all");
    }    
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void nacitStatZDatabaze() {
        String ids = context.getRequest().getParameter("stat.id");
        if (ids == null) return;
        stat = statManager.getStatById(Integer.parseInt(ids));
    }
 
    public Resolution edit() {
        log.debug("edit() stat={}", stat);
        return new ForwardResolution("/statyEdit.jsp");
    }
 
    public Resolution save() {
        log.debug("save() stat={}", stat);
        statManager.aktualizaceStatu(stat);
        return new RedirectResolution(this.getClass(), "all");
    }
        
    public Resolution storno() {
        log.debug("edit() stat={}", stat);
        return new RedirectResolution(this.getClass(), "all");
    }
    
}

Problem mam u tabulky adresa. SQL dotazy spustene v phpMyAdminu funguji dobre. Jak mam pracovat s cizim klicem v jave?:

package com.example.test.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper;
import org.springframework.stereotype.Repository;

@Repository("adresaManager")
public class AdresaManagerImpl implements AdresaManager {
    
    final static Logger log = LoggerFactory.getLogger(AdresaManagerImpl.class);

    public AdresaManagerImpl() {
        log.debug("vytvoren");
    }
    
    private JdbcTemplate jdbc;
    
    @Autowired
    public void setDataSource(DataSource dataSource) {
        log.debug("dataSource set to {}", dataSource);
        jdbc = new JdbcTemplate(dataSource);
    }
    
    private static final RowMapper<Adresa> ADRESA_MAPPER = new RowMapper<Adresa>() {
        @Override
        public Adresa mapRow(ResultSet rs, int i) throws SQLException {
            Adresa adresa = new Adresa();
            adresa.setId(rs.getInt("id"));
            adresa.setUlice(rs.getString("ulice"));            
            adresa.setCp(rs.getString("cp"));
            adresa.setMesto(rs.getString("mesto"));
            adresa.setPsc(rs.getString("psc"));
            adresa.setStat("X");
         //   adresa.setStat(Integer.toString(rs.getInt("stat")));
            return adresa;
        }
    };
    
    //mapuje data z ResultSet na tridu Stat
    /*
    private static final RowMapper<Stat> STAT_MAPPER = new RowMapper<Stat>() {
        @Override
        public Stat mapRow(ResultSet rs, int i) throws SQLException {
            Stat stat = new Stat();
            stat.setId(rs.getInt("id"));
            stat.setNazev(rs.getString("nazev"));
            return stat;
        }
    };
    */
    /*
    @SpringBean
    protected StatManager statManager;    
    */
    
    //mapuje jediny sloupec z ResultSet na String
    private static final ParameterizedSingleColumnRowMapper<String> STRING_MAPPER = ParameterizedSingleColumnRowMapper.newInstance(String.class);

    @Override
    public void vytvoritAdresu(Adresa adresa) {              
        //int statId = jdbc.queryForObject("SELECT id, nazev FROM stat WHERE nazev= ? LIMIT 1", STAT_MAPPER, 1).getId();
      //  int statId = statManager.getStatByNazev(adresa.getStat()).getId();
        int statId = 1;
        jdbc.update("INSERT INTO adresa (ulice, cp, mesto, psc, stat_id) VALUES (?,?,?,?,?)", 
                adresa.getUlice(), adresa.getCp(), adresa.getMesto(), 
                adresa.getPsc(), statId );
    }

    @Override
    public Adresa getAdresaById(int id) {
        return jdbc.queryForObject("SELECT * FROM adresa WHERE id = ?", ADRESA_MAPPER, id);
    }

    @Override
    public List<Adresa> getVsechnyAdresy() {
        return jdbc.query("SELECT adresa.id, adresa.ulice, adresa.cp, adresa.mesto, adresa.psc, stat.nazev AS stat FROM adresa INNER JOIN stat ON adresa.stat_id = stat.id ORDER BY adresa.mesto ASC", 
                ADRESA_MAPPER);
    }

    @Override
    public void aktualizaceAdresy(Adresa adresa) {        
        //int statId = jdbc.queryForObject("SELECT id, nazev FROM stat WHERE nazev= ? LIMIT 1", STAT_MAPPER, 1).getId();        
       // int statId = statManager.getStatByNazev(adresa.getStat()).getId();
        int statId = 1;
        jdbc.update("UPDATE adresa SET ulice=?, cp=?, mesto=?, psc=?, stat_id=? WHERE id=?",
                adresa.getUlice(), adresa.getCp(), adresa.getMesto(), adresa.getPsc(), statId );
    }

    @Override
    public void smazaniAdresy(Adresa adresa) {
        jdbc.update("DELETE FROM adresa WHERE id = ?", adresa.getId() );
    }    
}
/* --------------------------------------------------------- */
package com.example.test.web;

import com.example.test.model.Adresa;
import com.example.test.model.AdresaManager;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@UrlBinding("/adresy/{$event}/{adresa.id}")
public class AdresaActionBean implements ActionBean {
    
    final static Logger log = LoggerFactory.getLogger(AdresaActionBean.class);

    private ActionBeanContext context;
    
    @SpringBean
    protected AdresaManager adresaManager;    
    
    @DefaultHandler
    public Resolution all() {
        log.debug("all()");
        log.info("ALL ADRESY");
        return new ForwardResolution("/adresyShow.jsp");
    }
    
    public List<Adresa> getAdresy() {
        return adresaManager.getVsechnyAdresy();
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }
    
    @ValidateNestedProperties(value = {
            @Validate(on = {"add", "save"}, field = "ulice", required = true)
    })
    private Adresa adresa;

    public Adresa getAdresa() {
        return adresa;
    }

    public void setAdresa(Adresa adresa) {
        this.adresa = adresa;
    }
    
    public Resolution add() {
        log.debug("add() adresa={}", adresa);
        adresaManager.vytvoritAdresu(adresa);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution delete() {
        log.debug("delete({})", adresa.getId());
        adresaManager.smazaniAdresy(adresa);
        return new RedirectResolution(this.getClass(), "all");
    }    
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void nacitAdresuZDatabaze() {
        String ids = context.getRequest().getParameter("adresa.id");
        if (ids == null) return;
        adresa = adresaManager.getAdresaById(Integer.parseInt(ids));
    }
 
    public Resolution edit() {
        log.debug("edit() adresa={}", adresa);
        return new ForwardResolution("/adresyEdit.jsp");
    }
 
    public Resolution save() {
        log.debug("save() adresa={}", adresa);
        adresaManager.aktualizaceAdresy(adresa);
        return new RedirectResolution(this.getClass(), "all");
    }
        
    public Resolution storno() {
        log.debug("edit() adresa={}", adresa);
        return new RedirectResolution(this.getClass(), "all");
    }
    
}

Zde je cely kod: http://db.tt/L5y8OYY5

Muzete mi prosim nekdo poradit? Jinak obecne to delam dobre, nebo je to blbost a mam na to jit uplne jinak?

Dekuji za vase rady!

martin
MySQL › Jak moc je dobre pouzivat ul…
26. 8. 2013   #180830

#2 Jacques
>> btw: hesla by se neměla v databázi uchovávat uložená "natvrdo".

A jak tedy? Vzdyz v insertu mam:

INSERT INTO uzivatel (`login`, `heslo`, `adresa_id`) VALUES (login, SHA2(heslo,512), (SELECT id FROM adresa WHERE `ulice`=ulice AND `cp`=cp AND `mesto`=mesto AND `psc`=psc) );

ukladam heslo pomoci SHA-512 SHA2(heslo,512).

Myslis pridat salt? Napriklad  SHA2( CONCAT(login, heslo),512)?

martin
C / C++ › Arduino (C++) - zkraceni dob…
29. 3. 2013   #174050

Zdravim,

potrebuju v Arduinu zkracovat impulzy.

Na vstup mi prijde impulz, napr. 10ms ja ho potrebuju zkratit o vzdy stejnou hodnotu - napr. 20% a nastavit na vystup.

Takze vstup bude zapnuty 10ms a vystup bude zapnuty 8ms. Problem je, ze delka vstupu se meni, klidne tam muze byt treba 100ms a ja pak musim nastavit 80ms na vystup.

Arduino neumi (aspon tedy nevim jak) vice vlaken.

Kdyz pouziju nasledujici typ kodu:

int led = 13;
void setup() {               
  pinMode(led, OUTPUT);    
}
void loop() {
  digitalWrite(led, HIGH);
  delay(1000);
  digitalWrite(led, LOW);
  delay(1000);
}

Tak zapnu vystup a na stanovenou dobu zastavim cely program a pak teprve pokracuji, coz je nepripustne.

Napadlo me udelat nejaky casovac napr 1 mikrosekunda a vzdy ho zvetsovat o 1. U prodlouzeni pulzu si myslim, ze by problem nebyl. Jak ale vyresim zkraceni?

Zatim jsem napsal:

const byte in = 7; // namapovani pinu na I/O procesoru
const byte out = 8;

unsigned long minuly;
unsigned long casovacIn = 0;
unsigned long casovacOut = 0;
boolean inStav = 0;

byte konstanta = 20; // 20%

void setup() {
  pinMode(in, INPUT); // nataveni funkce pinu
  pinMode(out, OUTPUT);
}

void loop() {
  if (in == HIGH) {
    inStav = true;
    casovacIn++;
  } else {
    minuly = casovacIn;
    inStav = false;
    casovacIn = 0;
  }
  
  if (inStav && (minuly*konstanta/10) < casovacOut) {
    casovacOut++;
    digitalWrite(out, HIGH);
  } else {
    casovacOut = 0;
    digitalWrite(out, LOW);
  }
  
  delayMicroseconds(1);  
}

Je to dobry postup? Jak byste to resili vy?

Dekuji za pomoc!

Java › Tvorba vyukovych Java applet…
16. 2. 2013   #171592

#6 omiu
Java != JavaScript

Java › Tvorba vyukovych Java applet…
4. 2. 2013   #171093

#2 zlz
Jenze Java narozdil od Flashe pujde vsude. Zkus si treba rozjet Adobe Flash na Raspberry PI (ARM) - mas smulu. S Javou neni problem :-)

Java › Tvorba vyukovych Java applet…
18. 1. 2013   #170303

#2 zlz
>> Java applety jsou pochopitelně psané v Javě :)

Necekane :-D

Proste mi prijde divne, ze by kazdy applet vznikal uplne z niceho. Zvlast pri jejich velkem mnozstvi - internet jich je plny.

Napr. tato animace musela dat hodne prace.

Java › Tvorba vyukovych Java applet…
18. 1. 2013   #170295

Zdravim,

na Internetu jsem nasel velke mnozstvi vyukovych Java appletu, napr. na fyziku a matematiku.

Zarazilo mne, ze skoro zadne nejsou psane ve Flashi, ale v Jave. Mozna, ze v dobe vzniku appletu jeste flash moc rozsireny nebyl.

Ukazkove applety jsou treba na strance http://www.walter-fendt.de/ph14e/

Hlavne http://www.walter-fendt.de/ph14e/generator_e.htm a http://www.walter-fendt.de/ph14e/n2law.htm

Vzhledem k tomu, ze na desktopu take pisu v Jave a s Flashem mam nulove zkusenosti, rad bych zkusil nejaky podobny applet take vytvorit. Existuje nejaka knihovna? Nechce se mi verit, ze by byly vsechny applety psane v "ciste Jave".

Diky za rady :-)

Java › Zjisteni jmena JAR souboru u…
6. 11. 2012   #165979

#4 JoDiK

System.out.println(System.getProperty("sun.java.command"));

funguje:


C:\>java -jar arg.jar a b c
arg.jar a b c

C:\>
tux.martin
Java › Java - seriovy port
5. 11. 2012   #165891

#10 liborb
Diky, uz to funguje!

Jen jeste jeden detail. Mam: 

public void run() {
			byte[] buffer = new byte[1024];
			int len = 0;
			String nacteno = "";

			long start = System.currentTimeMillis();
			while (true) {
				try {
					len = this.in.read(buffer);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (len > 0) {
					nacteno += new String(buffer, 0, len);
					System.out.println("Nacteno: " + nacteno);
				} else
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				if ((System.currentTimeMillis() - start) > 5000)
					break;
			}	
			System.out.println("NactenoEND: " + nacteno);
		}

A po spusteni to vrati: 

Nacteno: S
Nacteno: STO
Nacteno: STOP
Nacteno: STOP_OK

Proc se vubec neprovede ten radek System.out.println("NactenoEND: " + nacteno); ?

Java › Zjisteni jmena JAR souboru u…
5. 11. 2012   #165889

Zdravim,

potrebuju nastavit programu vice pameti, ale nechci mit samostatny bat soubor, ktery by volal:

@ECHO OFF
java -Xss16M -jar soubor.jar

Podarilo se mi to cele nacpat do jednoho JAR souboru a funguje to:  

package app;

import java.awt.EventQueue;
import java.io.IOException;

public class Spustit {

  public static void main(String[] args) {

    if ((args.length != 0) && args[0].equals("xss_set")) {

      EventQueue.invokeLater(new Runnable() {
        public void run() {
          try {
            Okno frame = new Okno();
            frame.setVisible(true);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });

    } else {
      System.out.println("Není nastavená paměť! Nastavuji paměť a spouštím program znovu.");
      try {
        // TODO predat jmeno JAR souboru
        Runtime.getRuntime().exec("java -Xss16M -jar ./soubor.jar xss_set");
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

}

Problem je, kdyz nejaky "aktivni" uzivatel prejmenuje JAR soubor - pak to nejde.

Je nejaka funkcni moznost, jak muze program za sveho behu zjistit jmeno sveho jar souboru?

Nebo existuje nejake lepsi reseni, jak predat v programu JVM argumenty? Znovu spusteni noveho JVM se mi moc nelibi, ale lepsi reseni neznam :-(

Dekuji za pomoc!

martin
Java › Java - seriovy port
4. 11. 2012   #165853

#8 martin
Spletl jsem se, vypise to:

ABC: 
DelkaRetezce: 1
martin
Java › Java - seriovy port
4. 11. 2012   #165852

#6 sleepy

Tak jsem to upravil a porad to nejde:

V Hlavni tride mam:

serialPort.disableReceiveTimeout();
serialPort.disableReceiveThreshold();
import java.io.IOException;
import java.io.InputStream;

public class SerialReader extends Thread {
		InputStream in;

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int len = 0;
			String nacteno = "";
			try {				
				while ((len = this.in.read(buffer)) == -1) {
					nacteno = new String(buffer, 0, len);
					System.out.print("X: " + nacteno);
				}
				System.out.println("ABC: " + nacteno);
				System.out.println("DelkaRetezce: " + len); 
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}

Po spusteni to vypise:

B: 
DelkaRetezce: 1
martin
Java › Java - seriovy port
28. 10. 2012   #165472

Zapis uz mi funguje, ale nyni mam problem se ctenim. 

Do zarizeni poslu pismeno, zarizeni neco vykona a odesle zpet do PC nejaky text. Napr. kdyz poslu do zarizeni 'C', tak odpovi 'STOP'. Po odeslani 'C' do zarizeni reaguje spravne, ale na PC uz se mi nedari prescist 'STOP'. 

Zkousel jsem pridat  

serialPort.disableReceiveTimeout();
serialPort.enableReceiveThreshold(1);

coz jsem neasel v nejakem navodu, ale nepomohlo to.

Vystup po spusteni je: 

precteno: null

Muzete mi prosim poradit, kde je chyba? 

/* ##################################################### */
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.InputStream;
import java.io.OutputStream;

public class Hlavni {
	public static String nactenyText;
	private SerialPort serialPort;

	private void connect(String portName, int baudRate) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);

			if (commPort instanceof SerialPort) {
				//SerialPort serialPort = (SerialPort) commPort;
				serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				// http://mattiaslife.blogspot.cz/…locking.html
				
				serialPort.disableReceiveTimeout();
				serialPort.enableReceiveThreshold(1);
								
				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();
				
				new SerialReader(in).start();			
				new SerialWriter(out, 'a').start();
				new SerialWriter(out, 'c', 2000).start();	

				System.out.println("precteno: " + nactenyText);
				

			} else {
				System.out
						.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	public static void main(String[] args) {
		try {
			new Hlavni().connect("/dev/ttyUSB1", 57600);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
/* ##################################################### */
import java.io.IOException;
import java.io.InputStream;

public class SerialReader extends Thread {
		InputStream in;

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int len = 0;
			try {
				while ((len = this.in.read(buffer)) == -1) {
					Thread.sleep(10);
					String nacteno = new String(buffer, 0, len);
					System.out.print("ABC: " + nacteno);
					Hlavni.nactenyText = nacteno;
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
		
	}
/* ##################################################### */
import java.io.IOException;
import java.io.OutputStream;

public class SerialWriter extends Thread {
	OutputStream out;
	private char znak;
	private int uspat = 0;

	public SerialWriter(OutputStream out, char znak, int cekat) {
		this.out = out;
		this.znak = znak;
		this.uspat = cekat;
	}

	public SerialWriter(OutputStream out, char znak) {
		this.out = out;
		this.znak = znak;
	}

	public void run() {
		try {

			Thread.sleep(uspat);
			this.out.write(znak);

			this.out.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
/* ##################################################### */
martin
Java › Java - seriovy port
28. 10. 2012   #165464

#2 sleepy
Diky za pomoc. this.out.flush(); to vyresilo :-)

martin
Java › Java - seriovy port
22. 10. 2012   #165141

Ahoj, 

potrebuju v Jave komunikovat se zarizenim pripojenym na seriovy port (RS-232). Nyni mam program napsany a funkcni ve FreePascalu, potrebuji ho ale prepsat do Javy. Nasel jsem knihovnu RXTX. Vypada docela dobre, co si o ni myslite? http://rxtx.qbang.org/

Do zarizeni se posilaji prikazy ve forme pismen, napr. "E", zarizeni odpovi textem, napr. "+21.8", nebo "A_ON".

V Jave se mi to porad nedari.

Pokousim se upravit ukazkovy kod, co jsem nekde stahnul: 

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Test {
	public Test() {
		super();
	}

	void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();

				(new Thread(new SerialReader(in))).start();
				(new Thread(new SerialWriter(out))).start();

			} else {
				System.out
						.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	/** */
	public static class SerialReader implements Runnable {
		InputStream in;

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					System.out.print(new String(buffer, 0, len));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** */
	public static class SerialWriter implements Runnable {
		OutputStream out;

		public SerialWriter(OutputStream out) {
			this.out = out;
		}

		public void run() {
			try {


				// this.out.write(c);
				this.out.write('B');
			//	this.out.write('\r');
				//this.out.write('\n');

				// int c = 0;
				// while ((c = System.in.read()) > -1) {
				// this.out.write(c);
				// }
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		try {
			(new Test()).connect("/dev/ttyUSB0");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

ale porad to nejde. :-(

Muzete mi prosim nekdo poradit?

martin
Java › Java SSL socket, klietn a se…
3. 10. 2012   #164011

#8 martin
Tak jsem postupoval podle navodu: http://ruchirawageesha.blogspot.cz/2010/07/how-to-create-clientserver-keystores.html :

keytool -genkey -alias server -keyalg RSA -keystore server.jks
keytool -genkey -alias client -keyalg RSA -keystore client.jks
keytool -list -v -keystore server.jks
keytool -list -v -keystore server.jks -storepass pokus123
keytool -export -file server.cert -keystore server.jks -storepass pokus123 -alias server
keytool -export -file client.cert -keystore client.jks -storepass pokus123 -alias client
keytool -printcert -v -file server.cert
keytool -printcert -v -file client.cert
keytool -import -file client.cert -keystore server.jks -storepass pokus123 -alias client
keytool -import -file server.cert -keystore client.jks -storepass pokus123 -alias server
keytool -list -v -keystore server.jks -storepass pokus123
keytool -list -v -keystore client.jks -storepass pokus123

Kod jsem upravil:

SERVER: 

package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
 
public class SitServer {
	private int port;	
	private ServerSocket sslserver;

	public SitServer(int port) throws IOException {
		this.port = port;
		
		System.setProperty("javax.net.ssl.keyStore", "server.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "pokus123");
        SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
        sslserver = ssf.createServerSocket(port);	
	}

    public void handleConnection() {
        System.out.println("Waiting for client message...");
        while (true) {
            try {
            	Socket socket = sslserver.accept();
                //Socket socket = sslserver.accept();
                new ConnectionHandler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public int getPort() {
		return port;
	}
    
    public void setPort(int port) {
		this.port = port;
	}
    
}
 
class ConnectionHandler implements Runnable {
    private Socket socket;
 
    public ConnectionHandler(Socket socket) {
        this.socket = socket;
 
        Thread t = new Thread(this);
        t.start();
    }
 
    public void run() {
        try
        {
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
          
            if (message.equals("ABC")) {
            	System.out.println("Message Received: ABC " + message);
            	oos.writeObject("Prijato: " + message + "\n");
			} else if (message.equals("DEF")) {
				System.out.println("Message Received: DEF " + message);
				oos.writeObject("Prijato: " + message + "\n");
			} else {
				System.out.println("Message Received: JINE... "+  message);
				oos.writeObject("Prijato: " + message + "\n");
			} 
            ois.close();
            oos.close();
            socket.close();
 
            System.out.println("Waiting for client message...");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

KLIENT: 

package klient;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLSocketFactory;
 
public class SitKlient {	
	private Socket klient;
	
	public SitKlient(String host, int port) throws UnknownHostException, IOException {
		System.setProperty("javax.net.ssl.keyStore", "client.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "pokus123");
		SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
	    klient = socketFactory.createSocket(host, port);	
	}
	
	public void SocketWrite(String text) throws IOException {		
        ObjectOutputStream oos = new ObjectOutputStream(klient.getOutputStream());
        oos.writeObject(text);
        oos.flush();
	}
	
	public String SocketRead() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(klient.getInputStream());
        String message = (String) ois.readObject();
        return message;
	}

	public void SocketZavrit() throws IOException {
		klient.close();
	}
}	

Server se spusti bez problemu, ale klient zhavaruje:

Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
	at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
	at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:893)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:632)
	at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
	at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1847)
	at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1756)
	at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:230)
	at klient.SitKlient.SocketWrite(SitKlient.java:27)
	at klient.StartKlient.main(StartKlient.java:10)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
	at sun.security.validator.Validator.validate(Validator.java:218)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
	at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1185)
	... 12 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
	... 18 more

Kde delam tentokrat chybu? 

Jde nejak udelat keyStore na serveru s certifikatem serveru a jeho soukromym klicem bez nutnosti vkladat klientske certifikaty? A na klientu mit keyStore pouze s verejnym certifikatem serveru - tedy zadny klic a certifikat klienta. Je to mozne?

martin
Java › Java SSL socket, klietn a se…
2. 10. 2012   #164008

#7 Dano
Dekuji za rady.

Zkusim pouzit SSLServerSocketFactory, potrebuji totiz sifrovane spojeni.

Ne nesifrovane spojeni mi stacilo

import java.net.ServerSocket;

server = new ServerSocket(port);

Je nejaky rozdil mezi ServerSocketFactory a ServerSocket?

martin
Java › Java SSL socket, klietn a se…
30. 9. 2012   #163960

#2 Dano
V Eclipse spustim program jen jednou a hned to dela tento problem :-(

martin
Java › Java SSL socket, klietn a se…
29. 9. 2012   #163931

Zdravim, komunikace pres socket mi uz funguje, ale nyni potrebuji SSL.

Upravil jsem nasledovne kod:

Server:

StartServer.java:

package server;
import java.io.IOException;

public class StartServer {
	public static void main(String[] args) throws IOException {
		SitServer s = new SitServer("127.0.0.1", 4444);
		s.handleConnection();
	}
}

SitServer.java:

package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
 
public class SitServer {
	// http://www.kodejava.org/…les/216.html
	private String host;
	private int port;	
	private ServerSocket server;
	private ServerSocket ssocket;

	public SitServer(String host, int port) throws IOException {
		this.host = host;
		this.port = port;
		// http://www.exampledepot.com/…/Server.html
		ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
	    ssocket = ssocketFactory.createServerSocket(port);
	}

    public void handleConnection() {
        System.out.println("Waiting for client message...");
 
        while (true) {
            try {
            	Socket socket = ssocket.accept();
                new ConnectionHandler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public String getHost() {
		return host;
	}
    
    public void setHost(String host) {
		this.host = host;
	}
    
    public int getPort() {
		return port;
	}
    
    public void setPort(int port) {
		this.port = port;
	}
    
}
 
class ConnectionHandler implements Runnable {
    private Socket socket;
 
    public ConnectionHandler(Socket socket) {
        this.socket = socket;
 
        Thread t = new Thread(this);
        t.start();
    }
 
    public void run() {
        try
        {
            // Read a message sent by client application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            
            
            // Send a response information to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
          
            if (message.equals("ABC")) {
            	System.out.println("Message Received: ABC " + message);
            	oos.writeObject("Prijato: " + message + "\n");
			} else if (message.equals("DEF")) {
				System.out.println("Message Received: DEF " + message);
				oos.writeObject("Prijato: " + message + "\n");
			} else {
				System.out.println("Message Received: JINE... "+  message);
				oos.writeObject("Prijato: " + message + "\n");
			}
 
            ois.close();
            oos.close();
            socket.close();
 
            System.out.println("Waiting for client message...");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Klient

StartKlient.java:

package klient;

import java.io.IOException;
import java.net.UnknownHostException;

public class StartKlient {

	public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
		SitKlient sk = new SitKlient("127.0.0.1", 4444);
		sk.SocketWrite("ABC");
		System.out.println(sk.SocketRead());		
	}
}

SitKlient.java:

package klient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
 
public class SitKlient {	
	private Socket klient;
	
	public SitKlient(String host, int port) throws UnknownHostException, IOException {
		SocketFactory socketFactory = SSLSocketFactory.getDefault();
	    Socket klient = socketFactory.createSocket(host, port);
	}
	
	public void SocketWrite(String text) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(klient.getOutputStream());
        oos.writeObject(text);
        oos.flush();
	}
	
	public String SocketRead() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(klient.getInputStream());
        String message = (String) ois.readObject();
        return message;
	}

	public void SocketZavrit() throws IOException {
		klient.close();
	}
}

Hned pri spusteni serveru to spadne s: 

Exception in thread "main" java.net.BindException: Address already in use
	at java.net.PlainSocketImpl.socketBind(Native Method)
	at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:383)
	at java.net.ServerSocket.bind(ServerSocket.java:328)
	at java.net.ServerSocket.<init>(ServerSocket.java:194)
	at java.net.ServerSocket.<init>(ServerSocket.java:150)
	at javax.net.ssl.SSLServerSocket.<init>(SSLServerSocket.java:84)
	at com.sun.net.ssl.internal.ssl.SSLServerSocketImpl.<init>(SSLServerSocketImpl.java:81)
	at com.sun.net.ssl.internal.ssl.SSLServerSocketFactoryImpl.createServerSocket(SSLServerSocketFactoryImpl.java:58)
	at server.SitServer.<init>(SitServer.java:26)
	at server.StartServer.main(StartServer.java:6)

Kde delam chybu?

martin
Java › Java problem se sockety
29. 9. 2012   #163930

#2 Wizard
Diky, uz to funguje :-)

martin
Java › Graphics2D - vzdy spadne pri…
22. 9. 2012   #163580

#6 zlz
Diky moc, uz to funguje! :-)

Prikladam kompletni funkcni kod, kdyby ho v budoucnu nekdo potreboval: 

package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class Okno extends JFrame {

	private JPanel contentPane;
	private JPanel platno;
	private DrawImage di;
	private int oknoX = 320;
	private int oknoY = 240;	
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno frame = new Okno();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Okno() {
	setResizable(false);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setBounds(100, 100, oknoX, oknoY);
	contentPane = new JPanel();
	contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
	contentPane.setLayout(new BorderLayout(0, 0));
	setContentPane(contentPane);

	platno = new JPanel();		    
	platno.setLayout(new BorderLayout()); 
	this.getContentPane().add(platno, BorderLayout.CENTER);    
	di = new DrawImage(oknoX, oknoY);
	di.setBackground(Color.BLACK);
	platno.add(di, BorderLayout.CENTER);
	    
	di.kresliCaru(20, 20, 50, 70, Color.RED);
	di.kresliCtverec();              
	}
}
/* ----------------------------------------------------- */
package gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class DrawImage extends JPanel {
    private BufferedImage img;
    private int imgX = 320;
	private int imgY = 240;
	
	public DrawImage(int imgX, int imgY) {
		this.imgX = imgX;
		this.imgY = imgY;
	}

    private BufferedImage GetImage() {
        if (img == null) {
        	img = new BufferedImage(imgX, imgY, BufferedImage.TYPE_INT_RGB);
        }
        return img;
    }

    public void kresliCaru(int x1, int y1, int x2, int y2, Color barva) {
    	Graphics2D g = (Graphics2D) GetImage().createGraphics();
		g.setColor(barva);
		g.drawLine(x1, y1, x2, y2);			
	}
    
    public void kresliCtverec() {
    	Graphics2D g = (Graphics2D) GetImage().createGraphics();
    	g.drawRect(50, 60, 20, 40);		
	}

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, null);
    }
}
martin
Java › Graphics2D - vzdy spadne pri…
21. 9. 2012   #163570

#4 KIIV
Tak Graphics vytvarim ve tride Okno a predavam ji do tridy DrawImage:

package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

@SuppressWarnings("serial")
public class Okno extends JFrame {
	private JPanel contentPane;
	private JPanel platno;
	private DrawImage di;	
	private Graphics2D g;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno frame = new Okno();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Okno() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

	    platno = new JPanel();		    
	    platno.setLayout(new BorderLayout()); 
	    this.getContentPane().add(platno, BorderLayout.CENTER);    
	    di = new DrawImage(g);
	    di.setBackground(Color.BLACK);
	    platno.add(di, BorderLayout.CENTER);
	    
	    di.kresliCaru(0, 0, 20, 20, Color.RED);

	}
}
package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class DrawImage extends JPanel {	
	private Graphics2D gr;	
	public DrawImage(Graphics2D g) {
		this.gr = g;
	}
	@Override
	public void paintComponent(Graphics g1D) {
		gr = (Graphics2D) g1D;
	    gr.setColor(Color.RED);
	    gr.drawOval(0, 0, 50, 100);
	    gr.drawLine(10, 20, 50, 100);
	 }	
	public void kresliCaru(int x1, int y1, int x2, int y2, Color barva) {
		gr.setColor(barva);
		gr.drawLine(x1, y1, x2, y2);		
		gr.drawLine(10, 20, 50, 100);
	}
}

ale porad to nejde:

java.lang.NullPointerException
	at gui.DrawImage.kresliCaru(DrawImage.java:23)
	at gui.Okno.<init>(Okno.java:47)
	at gui.Okno$1.run(Okno.java:22)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
	at java.awt.EventQueue.access$000(EventQueue.java:101)
	at java.awt.EventQueue$3.run(EventQueue.java:666)
	at java.awt.EventQueue$3.run(EventQueue.java:664)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

:-(

martin
Java › Graphics2D - vzdy spadne pri…
21. 9. 2012   #163568

#2 Dano
Kdyz odkomentuju ten radek di.kresliCaru(0, 0, 20, 20, Color.RED); tak to hodi:

java.lang.NullPointerException
	at gui.DrawImage.kresliCaru(DrawImage.java:19)
	at gui.Okno.<init>(Okno.java:47)
	at gui.Okno$1.run(Okno.java:19)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
	at java.awt.EventQueue.access$000(EventQueue.java:101)
	at java.awt.EventQueue$3.run(EventQueue.java:666)
	at java.awt.EventQueue$3.run(EventQueue.java:664)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
martin
Java › Graphics2D - vzdy spadne pri…
21. 9. 2012   #163546

Ahoj, mam nasledujici kod:

// ####### Okno.java
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Okno extends JFrame {
	private JPanel contentPane;
	private JPanel platno;
	private DrawImage di;	
	private int x, y;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno frame = new Okno();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Okno() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

	    platno = new JPanel();		    
	    platno.setLayout(new BorderLayout()); 
	    this.getContentPane().add(platno, BorderLayout.CENTER);    
	    di = new DrawImage();

	    di.setBackground(Color.BLACK);
    //Ta barva se nikdy nenastavi :-(

	    platno.add(di, BorderLayout.CENTER);
	    
	    //di.kresliCaru(0, 0, 20, 20, Color.RED);
	    /*
    * Na tom to vzdycky spadne :-(
	     */
	}
}

// ####### DrawImage.java

package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

public class DrawImage extends JPanel {	
	private Graphics2D g;

	@Override
	public void paintComponent(Graphics g1D) {
		g = (Graphics2D) g1D;
	    g.setColor(Color.RED);
	    g.drawOval(0, 0, 50, 100);
	    g.drawLine(10, 20, 50, 100);
	 }
	
	public void kresliCaru(int x1, int y1, int x2, int y2, Color barva) {
		g.setColor(barva);
		g.drawLine(x1, y1, x2, y2);		
		g.drawLine(10, 20, 50, 100);
	}
}

Nikdy se mi nedari zmenit barvu pozadi. A kdyz zavolam metodu pro kresleni usecky, tak program vzdy pri kompilaci spadne ("di.kresliCaru(0, 0, 20, 20, Color.RED);").

Jinak program normalne funguje: http://www.imagehosting.cz/?…

Muzete mi prosim poradit, kde delam chybu?

m
Java › class extends JFrame - nefun…
20. 9. 2012   #163461

Ahoj, snazim se udelat jednoduche kreslitko.

Trida imgPanel je potomkem tridy javax.swing.JPanel a prekryva metodu paintComponent:

package gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class imgPanel extends JPanel{

	private BufferedImage buffer;
	private int sirka;
	private int vyska;
	
	public imgPanel() {
		sirka = 200;
		vyska = 200;
		buffer = new BufferedImage(sirka, vyska, BufferedImage.TYPE_3BYTE_BGR);
	}

	@Override
	public void paintComponent(Graphics g) {
        prepareImage();
        g.drawImage(buffer, 0, 0, null);
        g.dispose();
    }
    private void prepareImage() {
        Graphics g = buffer.createGraphics();
        g.drawLine(5, 5, 20, 50);
        g.setColor(Color.BLUE);
        g.dispose();
    }
    
    public int getSirka() {
		return sirka;
	}    
    public void setSirka(int sirka) {
		this.sirka = sirka;
	}    
    public int getVyska() {
		return vyska;
	}    
    public void setVyska(int vyska) {
		this.vyska = vyska;
	}        
}

A trida Okno pak pomoci JPanelu z tridy imgOkno zobrazi jednoduche kreslitko:

package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Okno extends JFrame {

	private JPanel contentPane;
	private JPanel abc;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno frame = new Okno();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Okno() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		abc = new imgPanel();	
	/* System.out.println(abc.getVyska); */
		contentPane.add(abc, BorderLayout.CENTER);      
	}
}

Kdyz se ale snazim v tride Okno zavolat metodu tridy imgPanel getVyska(), tak program vzdy spadne pri kompilaci.

Nevite, cim to muze byt?

martin
Java › JtextField nejde priradit Ab…
18. 9. 2012   #163408

#3 martin
Uz mi to funguje:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Okno {

	private JFrame frame;
	private JTextField textField;
	JLabel lblNewLabel;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno window = new Okno();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Okno() {
		initialize();
	}

	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 248, 158);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		final Action lblWrite = new AbstractAction("opsat text") {			
			@Override
			public void actionPerformed(ActionEvent e) {
				lblNewLabel.setText(textField.getText());				
			}
			
		};
		
		textField = new JTextField();
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				lblWrite.actionPerformed(new ActionEvent(this, (int) ActionEvent.KEY_EVENT_MASK, null));
			}
		});

		textField.setBounds(10, 11, 196, 20);
		textField.setAction(lblWrite);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		JButton btnNewButton = new JButton("New button");
		btnNewButton.setAction(lblWrite);
		btnNewButton.setBounds(10, 42, 196, 23);
		frame.getContentPane().add(btnNewButton);
		
		lblNewLabel = new JLabel("New label");
		lblNewLabel.setBounds(10, 76, 196, 14);
		frame.getContentPane().add(lblNewLabel);
	}
}
martin
Java › JtextField nejde priradit Ab…
18. 9. 2012   #163397

#2 sleepy
Aby prubeznym psanim do textfieldu dochazelo k napsani aktualniho obsahu textfieldu do labelu. Pri rucnim kliknuti na button to musi taky prepsat textfield do labelu.

martin
Java › JtextField nejde priradit Ab…
18. 9. 2012   #163364

Zdravim, snazim se udelat jednoduchy program, ktery prepise text z textfieldu do labelu.

Protoze potrebuju opisovat po praci s  vice ovladacimi prvky, tak to asi musim resit akci.

Kdyz priradim akci buttonu, neni problem. Kdyz ji ale dam textfieldu, tak to nic nedela. Pritom kdyz textfildu pridam KeyListener(keyReleased) tak to funguje.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Okno {

	private JFrame frame;
	private JTextField textField;
	JLabel lblNewLabel;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno window = new Okno();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Okno() {
		initialize();
	}

	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 248, 158);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		Action lblWrite = new AbstractAction("opsat text") {			
			@Override
			public void actionPerformed(ActionEvent e) {
				lblNewLabel.setText(textField.getText());				
			}
		};
		
		textField = new JTextField();
		/* //funguje
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				lblNewLabel.setText(textField.getText());
			}
		});
		*/
		textField.setBounds(10, 11, 196, 20);
		textField.setAction(lblWrite);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		JButton btnNewButton = new JButton("New button");
		btnNewButton.setAction(lblWrite);
		btnNewButton.setBounds(10, 42, 196, 23);
		frame.getContentPane().add(btnNewButton);
		
		lblNewLabel = new JLabel("New label");
		lblNewLabel.setBounds(10, 76, 196, 14);
		frame.getContentPane().add(lblNewLabel);
	}
}

Poradite mi prosim, kde delam chyu a jak ji opravit?

martin
Java › Java problem se sockety
16. 9. 2012   #163252

Zdravim,

snazim se v Jave naprogramovat jednoduche socketovou aplikaci (klient a server).

   Server:

StartServer.java:

package server;

import java.io.IOException;
public class StartServer {

/**
  * @param args
  * @throws IOException
  */
public static void main(String[] args) throws IOException {
  SitServer s = new SitServer("127.0.0.1", 4444);
  s.handleConnection();

}
}

SitServer.java:

package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;

public class SitServer {
// http://www.kodejava.org/…les/216.html
private String host;
private int port;
private ServerSocket server;
public SitServer(String host, int port) throws IOException {
  this.host = host;
  this.port = port;
  server = new ServerSocket(port);
}

    public void handleConnection() {
        System.out.println("Waiting for client message...");

        // The server do a loop here to accept all connection initiated by the
        // client application.
        while (true) {
            try {
                Socket socket = server.accept();
                new ConnectionHandler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
    public String getHost() {
  return host;
}
   
    public void setHost(String host) {
  this.host = host;
}
   
    public int getPort() {
  return port;
}
   
    public void setPort(int port) {
  this.port = port;
}
   
}

class ConnectionHandler implements Runnable {
    private Socket socket;

    public ConnectionHandler(Socket socket) {
        this.socket = socket;

        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        try
        {
            // Read a message sent by client application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
           
           
            // Send a response information to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
         
            if (message.equals("ABC")) {
             System.out.println("Message Received: ABC " + message);
             oos.writeObject("Prijato: " + message + "\n");
   } else if (message.equals("DEF")) {
    System.out.println("Message Received: DEF " + message);
    oos.writeObject("Prijato: " + message + "\n");
   } else {
    System.out.println("Message Received: JINE... "+  message);
    oos.writeObject("Prijato: " + message + "\n");
   }
            //System.out.println("Message Received: " + message);      

            ois.close();
            oos.close();
            socket.close();

            System.out.println("Waiting for client message...");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

   Klient

StartKlient.java:

package klient;

import java.io.IOException;
import java.net.UnknownHostException;
public class StartKlient {

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
  SitKlient sk = new SitKlient("127.0.0.1", 4444);
  sk.SocketWrite("ABC");
  System.out.println(sk.SocketRead());
 
}

}

SitKlient.java:

package klient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.Socket;
import java.net.UnknownHostException;

public class SitKlient {
private int port;
private String host;
private Socket klient;

public SitKlient(String host, int port) throws UnknownHostException, IOException {
  this.host = host;
  this.port = port;
 
  klient = new Socket(host, port);
}

public void SocketWrite(String text) throws IOException {
        // Send a message to the client application
        ObjectOutputStream oos = new ObjectOutputStream(klient.getOutputStream());
        //oos.writeObject("Hello There...");
        oos.writeObject(text);
        oos.close();
}

public String SocketRead() throws IOException, ClassNotFoundException {
        // Read and display the response message sent by server application
        ObjectInputStream ois = new ObjectInputStream(klient.getInputStream());
        String message = (String) ois.readObject();
        //System.out.println("Message: " + message);
        ois.close();
        return message;
}
public void SocketZavrit() throws IOException {
  klient.close();
}

}

Spustim server a pote klient a spadne to s:

Waiting for client message...
Message Received: ABC ABC
java.net.SocketException: Software caused connection abort: socket write error
	at java.net.SocketOutputStream.socketWrite0(Native Method)
	at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
	at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
	at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1857)
	at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1766)
	at java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1273)
	at java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1227)
	at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1411)
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
	at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1557)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
	at server.ConnectionHandler.run(SitServer.java:80)
	at java.lang.Thread.run(Thread.java:722)

Nevite, kde delam chybu? Vzdyt je videt, ze server zpravu prijme.

Dalo by se nejak pri spusteni vyhazet ty vyjimky throws?

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException {
  SitKlient sk = new SitKlient("127.0.0.1", 4444);
  sk.SocketWrite("ABC");
  System.out.println(sk.SocketRead());
 
}

Zdrojovy kod: http://www.uloz.to/…cket-src-zip

Dekuji za radu :-)

 

 

Hostujeme u Českého hostingu       ISSN 1801-1586       ⇡ Nahoru Webtea.cz logo © 20032024 Programujte.com
Zasadilo a pěstuje Webtea.cz, šéfredaktor Lukáš Churý