esoe 2 years ago
parent
commit
56c1f090d2
  1. 39
      java/samples/introduction/A.java
  2. 29
      java/samples/introduction/B.java
  3. 28
      java/samples/introduction/C.java
  4. BIN
      java/samples/introduction/DEV-J110.01. Основы ООП.pdf
  5. BIN
      java/samples/introduction/DEV-J110.02. Обзор платформы.pdf
  6. BIN
      java/samples/introduction/DEV-J110.03. Классы.pdf
  7. BIN
      java/samples/introduction/DEV-J110.04. Наследование классов.pdf
  8. BIN
      java/samples/introduction/DEV-J110.05. Специальные виды классов.pdf
  9. BIN
      java/samples/introduction/DEV-J110.06. Интерфейсы.pdf
  10. 24
      java/samples/introduction/I.java
  11. BIN
      java/samples/java-packages/DEV-J120.SE.4.1.AWT.pdf
  12. 35
      java/samples/java-packages/source/DemoActionListener.java
  13. 135
      java/samples/java-packages/source/DemoCollection.java
  14. 24
      java/samples/java-packages/source/DemoFunInterface.java
  15. 25
      java/samples/java-packages/source/DemoInteger.java
  16. 63
      java/samples/java-packages/source/DemoJFrame.java
  17. 52
      java/samples/java-packages/source/DemoLambda.java
  18. 38
      java/samples/java-packages/source/DemoObject.java
  19. 41
      java/samples/java-packages/source/DemoRuntime.java
  20. 27
      java/samples/java-packages/source/DemoString.java
  21. 22
      java/samples/java-packages/source/DemoWindowAdapter.java
  22. 53
      java/samples/java-packages/source/DemoWindowListener.java
  23. 15
      java/samples/java-packages/source/EmptyStackException.java
  24. 15
      java/samples/java-packages/source/FullStackException.java
  25. 38
      java/samples/java-packages/source/Stack.java
  26. 27
      java/samples/multithread/ping-pong/Ball.java
  27. BIN
      java/samples/multithread/ping-pong/DEV-J130.1.Введение.pdf
  28. BIN
      java/samples/multithread/ping-pong/DEV-J130.2.Основы SQL.pdf
  29. BIN
      java/samples/multithread/ping-pong/DEV-J130.4.Многопоточность.pdf
  30. BIN
      java/samples/multithread/ping-pong/DEV-J130.5.Сетевое взаимодействие.pdf
  31. 31
      java/samples/multithread/ping-pong/DemoThread.java
  32. 54
      java/samples/multithread/ping-pong/PingPong.java
  33. 40
      java/samples/multithread/ping-pong/SimpleThread.java
  34. 158
      java/samples/multithread/ping-pong/UDPClient.java
  35. 120
      java/samples/multithread/ping-pong/UDPServer.java

39
java/samples/introduction/A.java

@ -0,0 +1,39 @@ @@ -0,0 +1,39 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
/**
*
* @author (C)Y.D.Zakovryashin, 07.10.2022
*/
public class A {
private A a;
private A b;
public A () {
this(null);
System.out.println ("A::A()");
}
public A (A a) {
System.out.println("A::A(A)");
}
public void a () {
System.out.println("A::a()");
}
public void a (A a) {
System.out.println("A::a(A)");
}
public static void main (String[] args) {
System.out.println("Hello, Java!!!");
A a = new A (null);
a.a(a);
}
}

29
java/samples/introduction/B.java

@ -0,0 +1,29 @@ @@ -0,0 +1,29 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
/**
*
* @author (C)Y.D.Zakovryashin, 07.10.2022
*/
public class B extends A {
public B() {
super(null); // this();
System.out.println("B::B()");
}
public static void main(String[] args) {
B b = new B();
b.a();
}
@Override
public void a() {
System.out.println("B::a()");
super.a();
}
}

28
java/samples/introduction/C.java

@ -0,0 +1,28 @@ @@ -0,0 +1,28 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
/**
*
* @author (C)Y.D.Zakovryashin, 07.10.2022
*/
public class C implements I {
public void a() {
System.out.println("C::a()");
}
public void a(A a) {
System.out.println("C::a(A)");
}
public static void main(String[] args) {
C c = new C();
c.a();
c.a(null);
c.b();
}
}

BIN
java/samples/introduction/DEV-J110.01. Основы ООП.pdf

Binary file not shown.

BIN
java/samples/introduction/DEV-J110.02. Обзор платформы.pdf

Binary file not shown.

BIN
java/samples/introduction/DEV-J110.03. Классы.pdf

Binary file not shown.

BIN
java/samples/introduction/DEV-J110.04. Наследование классов.pdf

Binary file not shown.

BIN
java/samples/introduction/DEV-J110.05. Специальные виды классов.pdf

Binary file not shown.

BIN
java/samples/introduction/DEV-J110.06. Интерфейсы.pdf

Binary file not shown.

24
java/samples/introduction/I.java

@ -0,0 +1,24 @@ @@ -0,0 +1,24 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
/**
*
* @author (C)Y.D.Zakovryashin, 07.10.2022
*/
public interface I {
public static final A a = new A(null);
A b = null;
public abstract void a();
void a(A a);
default void b() {
System.out.println("I:b() - default");
}
}

BIN
java/samples/java-packages/DEV-J120.SE.4.1.AWT.pdf

Binary file not shown.

35
java/samples/java-packages/source/DemoActionListener.java

@ -0,0 +1,35 @@ @@ -0,0 +1,35 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* @author (C)Y.D.Zakovryashin, 28.11.2022
*/
public class DemoActionListener implements ActionListener{
private Container cp;
private Color defaultColor;
public DemoActionListener ( Container cp) {
this.cp = cp;
defaultColor = cp.getBackground();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println ("Action performed");
Color c = cp.getBackground();
cp.setBackground(c == defaultColor ? Color.BLUE : defaultColor) ;
}
}

135
java/samples/java-packages/source/DemoCollection.java

@ -0,0 +1,135 @@ @@ -0,0 +1,135 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package std;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*
* @author (C)Y.D.Zakovryashin, 05.12.2022
*/
public class DemoCollection {
public class User implements Serializable {
private String login;
private String password;
public User(String login, String password) {
this.login = login;
this.password = password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" + "login=" + login + ", password=" + password + '}';
}
}
public class Info implements Serializable {
String info;
public Info(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String toString() {
return "Info{" + "info=" + info + '}';
}
}
public static void main(String[] args) {
DemoCollection demo = new DemoCollection();
// demo.print(demo.init(5));
Map<User, Info> m = demo.init();
demo.printMap(m);
}
private Set<Integer> init(int size) {
int[] ai = {123, 345, 4564, 345, 123};
HashSet<Integer> hs = new HashSet<>();
for (int i : ai) {
System.out.println("Add " + i + " is "
+ hs.add(new Integer(i)));
}
return hs;
}
private Map<User, Info> init() {
HashMap<User, Info> hm = new HashMap<>();
hm.put(new User("first", "12344"), new Info("first message"));
hm.put(new User("second", "283479"), new Info("secondt message"));
return hm;
}
private <T> void printIterator(Collection<T> c) {
if (c == null || c.isEmpty()) {
System.out.println("Collection is null or empty");
return;
}
Iterator<T> i = c.iterator();
while (i.hasNext()) {
T t = i.next();
System.out.println(t);
}
}
private <T> void print(Collection<T> c) {
if (c == null || c.isEmpty()) {
System.out.println("Collection is null or empty");
return;
}
for (T t : c) {
System.out.println(t);
}
}
private void printMap(Map<User, Info> m) {
// 1. Map.Entry
for (Map.Entry<User, Info> tm : m.entrySet()) {
System.out.println( tm.getKey() + " --> "
+ tm.getValue());
}
System.out.println("------------------------------");
// 2. keySet -> get(...)
for (User u : m.keySet()) {
Info i = m.get(u);
System.out.println(u + " --> " + i);
}
}
}

24
java/samples/java-packages/source/DemoFunInterface.java

@ -0,0 +1,24 @@ @@ -0,0 +1,24 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package std;
/**
*
* @author (C)Y.D.Zakovryashin, 05.12.2022
*/
@FunctionalInterface
public interface DemoFunInterface {
public String message(int x);
public static String info() {
return "Demo Functional interface";
}
default public void demo () {
System.out.println("Demo method");
}
}

25
java/samples/java-packages/source/DemoInteger.java

@ -0,0 +1,25 @@ @@ -0,0 +1,25 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
/**
*
* @author (C)Y.D.Zakovryashin, 14.11.2022
*/
public class DemoInteger {
public static void main(String[] args) {
Integer i = new Integer ("1234");
Integer j = Integer.valueOf("12345", 7);
Integer k = ++i;
i = ++i;
String s = "asdf";
s += "gth";
String t = new String (s);
System.out.println("s: " + s);
System.out.println(k);
}
}

63
java/samples/java-packages/source/DemoJFrame.java

@ -0,0 +1,63 @@ @@ -0,0 +1,63 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* @author (C)Y.D.Zakovryashin, 28.11.2022
*/
public class DemoJFrame extends JFrame {
private JLabel lbl;
public DemoJFrame(String title) {
super(title);
// setBounds (x, y, w, h);
// setTitle (title);
setLocation(120, 80);
setSize(640, 480);
setResizable(false);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
init();
setVisible(true);
}
public static void main(String[] args) {
DemoJFrame demo = new DemoJFrame("Demo JFrame");
}
private void init() {
// DemoWindowListener wl = new DemoWindowListener();
// addWindowListener(wl);
addWindowListener(new DemoWindowAdapter());
Container cp = getContentPane();
cp.setLayout(null);
// cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));
lbl = new JLabel("Demo label");
lbl.setBounds(120, 80, 160, 32);
JButton b = new JButton("Demo button");
b.setBounds(120, 140, 160, 32);
b.addActionListener(new DemoActionListener(cp));
// class ? implements ActionListener { .... }
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s = lbl.getText();
lbl.setText(s + "*");
}
});
cp.add(lbl);
cp.add(b);
}
}

52
java/samples/java-packages/source/DemoLambda.java

@ -0,0 +1,52 @@ @@ -0,0 +1,52 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package std;
import java.util.ArrayList;
/**
*
* @author (C)Y.D.Zakovryashin, 05.12.2022
*/
public class DemoLambda {
public static void main(String[] args) {
DemoLambda demo = new DemoLambda();
ArrayList<Integer> al = demo.init();
demo.print(al);
al.removeIf((Integer x) -> x % 2 != 0);
demo.print(al);
al.forEach((Integer x) -> {
System.out.print(x * 2 + ", ");
});
System.out.println("");
}
private ArrayList<Integer> init() {
int[] ai = {1, 2, 3, 4, 5, 6, 77, 78};
ArrayList<Integer> al = new ArrayList<>();
for (int i : ai) {
al.add(i);
}
return al;
}
private void a(int x) {
// new ? implements DemoFunInterface { ... }
DemoFunInterface d = x1 -> {
return String.valueOf(x1);
};
}
private void print(ArrayList<Integer> al) {
for (Integer i : al) {
System.out.print(i + ", ");
}
System.out.println();
}
}

38
java/samples/java-packages/source/DemoObject.java

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
/**
*
* @author (C)Y.D.Zakovryashin, 14.11.2022
*/
public class DemoObject implements Cloneable {
private int id = 12344;
public static void main(String[] args) {
DemoObject obj = new DemoObject();
System.out.println("obj: " + obj.id);
try {
DemoObject clone = (DemoObject) obj.clone();
System.out.println("clone: " + clone.id );
DemoObject clone2 = (DemoObject) clone.clone();
System.out.println("clone2: " + clone2.id );
} catch (CloneNotSupportedException e) {
System.out.println("Error: " + e.getMessage());
}
}
@Override
public Object clone () throws CloneNotSupportedException {
DemoObject t = new DemoObject(); // id = 12344
// DemoObject t = (DemoObject) super.clone();
t.id = id + 1; // id = 12345
if ( t.id > 1000000) {
throw new CloneNotSupportedException ("Id overflow");
}
return t;
}
}

41
java/samples/java-packages/source/DemoRuntime.java

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author (C)Y.D.Zakovryashin, 14.11.2022
*/
public class DemoRuntime {
private String cmd = "calc.exe";
public static void main(String[] args) {
new DemoRuntime().run();
}
public void run() {
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(cmd);
p.waitFor(5, TimeUnit.SECONDS);
if (p.isAlive()) {
System.out.println("Process is alive");
p.destroyForcibly();
} else {
System.out.println("Process is done");
}
System.out.println("Exit code: " + p.exitValue());
} catch (IOException | InterruptedException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
}

27
java/samples/java-packages/source/DemoString.java

@ -0,0 +1,27 @@ @@ -0,0 +1,27 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
/**
*
* @author (C)Y.D.Zakovryashin, 14.11.2022
*/
public class DemoString {
public static void main(String[] args) {
String s = "askjfsj akfkdjfal askdfjlasj asldkjflasj 1234";
// String[] as = s.split("\\s+");
// for (String t: as) {
// System.out.println(t);
// }
System.out.println(s.replaceAll("\\p{Digit}", "*"));
String n = "2202 2202 2222 2222";
String t = n.substring(5, 14);
String x = "**** ****";
n = n.replace(t, x);
System.out.println(n);
}
}

22
java/samples/java-packages/source/DemoWindowAdapter.java

@ -0,0 +1,22 @@ @@ -0,0 +1,22 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
*
* @author (C)Y.D.Zakovryashin, 28.11.2022
*/
public class DemoWindowAdapter extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
e.getWindow().dispose();
}
}

53
java/samples/java-packages/source/DemoWindowListener.java

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
/**
*
* @author (C)Y.D.Zakovryashin, 28.11.2022
*/
public class DemoWindowListener implements WindowListener {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("Window opened");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
e.getWindow().dispose();
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("Window closed");
}
@Override
public void windowIconified(WindowEvent e) {
System.out.println("Window iconified");
}
@Override
public void windowDeiconified(WindowEvent e) {
System.out.println("Window deiconified");
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("Window activated");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("Window deactivated");
}
}

15
java/samples/java-packages/source/EmptyStackException.java

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
/**
*
* @author (C)Y.D.Zakovryashin, 07.11.2022
*/
class EmptyStackException extends Exception {
}

15
java/samples/java-packages/source/FullStackException.java

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
/**
*
* @author (C)Y.D.Zakovryashin, 07.11.2022
*/
class FullStackException extends Exception {
}

38
java/samples/java-packages/source/Stack.java

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lang;
/**
*
* @author (C)Y.D.Zakovryashin, 07.11.2022
*/
public class Stack <T> {
public final int DEFAULT_SIZE = 128;
private T[] stack;
private int top;
public Stack(T[] stack) {
// size = size < 1 ? DEFAULT_SIZE : size;
this.stack = stack;
top = 0;
}
public void push(T x) throws FullStackException {
if (top == DEFAULT_SIZE) {
throw new FullStackException();
}
stack[top] = x;
++top;
}
public T pop() throws EmptyStackException {
if (top < 1) {
throw new EmptyStackException();
}
return stack[--top];
}
}

27
java/samples/multithread/ping-pong/Ball.java

@ -0,0 +1,27 @@ @@ -0,0 +1,27 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mt;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author (C)Y.D.Zakovryashin, 09.01.2023
*/
public class Ball {
public synchronized void hit(String name, int delay) {
System.out.print(name + " -> ");
try {
notify();
wait();
Thread.currentThread().sleep(delay);
} catch (InterruptedException ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
}

BIN
java/samples/multithread/ping-pong/DEV-J130.1.Введение.pdf

Binary file not shown.

BIN
java/samples/multithread/ping-pong/DEV-J130.2.Основы SQL.pdf

Binary file not shown.

BIN
java/samples/multithread/ping-pong/DEV-J130.4.Многопоточность.pdf

Binary file not shown.

BIN
java/samples/multithread/ping-pong/DEV-J130.5.Сетевое взаимодействие.pdf

Binary file not shown.

31
java/samples/multithread/ping-pong/DemoThread.java

@ -0,0 +1,31 @@ @@ -0,0 +1,31 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mt;
/**
*
* @author (C)Y.D.Zakovryashin, 09.01.2023
*/
public class DemoThread {
public static void main(String[] args) {
SimpleThread t1 = new SimpleThread('*', 10);
SimpleThread t2 = new SimpleThread('a', 10);
SimpleThread t3 = new SimpleThread('$', 10);
Thread mt = new Thread(t1, "First");
Thread m1 = new Thread(t2, "Second");
Thread m2 = new Thread(t3, "Third");
m2.setPriority(2);
mt.setPriority(7);
mt.start();
m1.start();
m2.start();
System.out.println(m2.getId() + "." + m2.getName() + ", "
+ m2.getPriority());
}
}

54
java/samples/multithread/ping-pong/PingPong.java

@ -0,0 +1,54 @@ @@ -0,0 +1,54 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mt;
/**
*
* @author (C)Y.D.Zakovryashin, 09.01.2023
*/
public class PingPong implements Runnable {
public static final int ROUND = 10;
private String name;
private int delay;
private Ball ball;
public PingPong(String name, int delay, Ball ball) {
this.name = name;
this.delay = delay;
this.ball = ball;
}
public static void main(String[] args) throws InterruptedException {
Ball ball = new Ball();
PingPong gamer1 = new PingPong("ping", 300, ball);
PingPong gamer2 = new PingPong("pong", 500, ball);
Thread t1 = new Thread(gamer1);
Thread t2 = new Thread(gamer2);
System.out.println("Start game...");
t1.start();
t2.start();
try {
t1.join(8000);
t2.join(8000);
synchronized (ball) {
ball.notifyAll();
}
} catch (InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("End over.");
}
@Override
public void run() {
for (int i = 0; i < ROUND; ++i) {
ball.hit(name, delay);
}
}
}

40
java/samples/multithread/ping-pong/SimpleThread.java

@ -0,0 +1,40 @@ @@ -0,0 +1,40 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mt;
/**
*
* @author (C)Y.D.Zakovryashin, 09.01.2023
*/
public class SimpleThread implements Runnable {
private char c;
private int num;
public SimpleThread(char c, int num) {
this.c = c;
this.num = num;
}
@Override
public void run() {
for (int i = 0; i < num; ++i) {
System.out.print("-" + c);
// try {
// Thread.currentThread().sleep(500);
// } catch (InterruptedException e) {
// System.out.println("Thread \""
// + Thread.currentThread().getName()
// + "\" is interrupted");
// }
}
System.out.println();
}
public Thread getThread () {
return Thread.currentThread();
}
}

158
java/samples/multithread/ping-pong/UDPClient.java

@ -0,0 +1,158 @@ @@ -0,0 +1,158 @@
/*
* Демонстрационное приложение.
*/
package udp;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
/**
* Класс клиента. Реализует запрос и получение файла от сервера.
*
* @author (C)Y.D.Zakovryashin, 16.01.2023
*/
public class UDPClient {
private DatagramSocket socket;
private DatagramPacket packet;
private byte[] buffer;
private String fileName;
public static void main(String[] args) {
System.out.println("Client started...");
try (DatagramSocket s = new DatagramSocket()) {
UDPClient client = new UDPClient();
client.socket = s;
/**
* Запрос у пользователя имени файла для загрузки.
*/
client.getFileName();
/**
* Запрос файла с сервера.
*/
client.sendFileName();
/**
* Чтение ответа сервера, содержащего либо размер файла, либо код
* ERROR, который означает отсутствие запрошенного файла на сервере.
*/
long size = client.getFileSize();
if (size > UDPServer.ERROR) {
try {
/**
* Загрузка файла с сервера.
*/
client.getFile(size);
System.out.println("File \"" + client.fileName
+ "\" is downloaded successfully.");
} catch (IOException e) {
/**
* Произошла ошибка чтения файла.
*/
System.err.println("File \"" + client.fileName
+ "\" isn\'t downloaded.\n" + e.getMessage());
}
} else {
/**
* Сервер вернул код ERROR, который означает, что на сервере нет
* файла с запрошенным именем.
*/
System.out.println("File \"" + client.fileName + "\" not found");
}
} catch (SocketException ex) {
System.out.println("Error #1: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("Error #2: " + ex.getMessage());
}
System.out.println("Client stoped.");
}
/**
* Чтение имени запрашиваемого файла с консоли.
*
* @return строку с именем файла.
*/
private void getFileName() {
try (BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));) {
/**
* Цикл запроса имени файла должен выполняться до тех пор, пока
* пользователь не введёт непустое имя файла.
*/
do {
System.out.println(">>> Input file name for download:");
fileName = in.readLine();
} while (fileName == null || fileName.trim().isEmpty());
} catch (IOException e) {
System.out.println("Errror: " + e.getMessage());
}
System.out.println("Step 1");
}
/**
* Отправка запроса с именем файла.
*
* @param fileName строка с именем файла.
* @throws IOException в случае общей ошибки ввода/вывода.
*/
private void sendFileName() throws IOException {
buffer = fileName.getBytes();
/**
* В пакет заносится адрес сервера, его порт и сериализованное имя
* файла.
*/
packet = new DatagramPacket(buffer, buffer.length,
InetAddress.getByName(UDPServer.UDP_SERVER_ADDRESS),
UDPServer.UDP_SERVER_PORT);
socket.send(packet);
System.out.println("Step 2");
}
/**
* Получение первого пакета от сервера с размером файла и отправка пакета с
* подтверждением о готовности принять файл.
*
* @return размер файла.
* @throws IOException в случае общей ошибки ввода/вывода.
*/
private long getFileSize() throws IOException {
buffer = new byte[8];
packet = new DatagramPacket(buffer, buffer.length);
/**
* Получение пакета с размером файла.
*/
socket.receive(packet);
long size = ByteBuffer.wrap(packet.getData()).getLong();
if (size > UDPServer.ERROR && size < Integer.MAX_VALUE) {
buffer = UDPServer.OK.getBytes();
} else {
buffer = UDPServer.NO.getBytes();
}
/**
* Подготовка и отправка пакета с подтверждением о готовности принять
* файл.
*/
packet.setData(buffer);
packet.setLength(buffer.length);
socket.send(packet);
System.out.println("Step 3");
return size;
}
private void getFile(long size) throws IOException {
int s = size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
buffer = new byte[s];
packet.setData(buffer);
socket.receive(packet);
try (FileOutputStream fos = new FileOutputStream("Copy-" + fileName)) {
fos.write(buffer);
}
System.out.println("Step 4");
}
}

120
java/samples/multithread/ping-pong/UDPServer.java

@ -0,0 +1,120 @@ @@ -0,0 +1,120 @@
/*
* Демонстрационное приложение. Сервер приложения.
*/
package udp;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
/**
* Класс сервера. Обеспечивает отправку клиенту запрошенного файла.
*
* @author (C)Y.D.Zakovryashin, 16.01.2023
*/
public class UDPServer {
public static final int UDP_SERVER_PORT = 12345;
public static final String UDP_SERVER_ADDRESS = "localhost";
public static final String OK = "Ok";
public static final String NO = "No";
public static final int ERROR = -1;
public static final int BUFFER_SIZE = 255;
private DatagramSocket socket;
private DatagramPacket packet;
private byte[] buffer;
private String fileName;
private long fileLength;
private boolean exists;
public static void main(String[] args) {
System.out.println("Server started...");
try (DatagramSocket s = new DatagramSocket(UDP_SERVER_PORT)) {
UDPServer server = new UDPServer();
server.socket = s;
/**
* Ожидание запроса клиента с именем файла.
*/
server.getFileName();
/**
* Отправка клиенту результата поиска файла: либо размера найденного
* файла, либо кода ERROR, который означает отсутствие запрошенного
* файла на сервере.
*/
server.sendResult();
/**
* Отправка файла с сервера.
*/
if (server.exists && server.getClientReply()) {
server.sendFile();
System.out.println("Server: File \"" + server.fileName
+ "\" is sent successfully.");
}
} catch (SocketException ex) {
System.out.println("Server error #1: " + ex.getMessage());
} catch (IOException e) {
/**
* Произошла ошибка ввода/вывода файла.
*/
System.err.println("Server error #2: " + e.getMessage());
}
System.out.println("Server stoped.");
}
/**
* Чтение имени запрашиваемого файла с консоли.
*
* @return строку с именем файла.
*/
private void getFileName() throws IOException {
buffer = new byte[BUFFER_SIZE];
packet = new DatagramPacket(buffer, BUFFER_SIZE);
socket.receive(packet);
fileName = new String(packet.getData(), 0, packet.getLength());
System.out.println("Step 1: file name: " + fileName);
}
private void sendResult() throws IOException {
File f = new File(fileName);
buffer = new byte[8];
if (exists = f.exists()) {
fileLength = f.length();
ByteBuffer.wrap(buffer).putLong(fileLength);
} else {
ByteBuffer.wrap(buffer).putLong(ERROR);
}
packet.setData(buffer);
packet.setLength(8);
socket.send(packet);
System.out.println("Step 2");
}
private boolean getClientReply() throws IOException {
buffer = new byte[4];
packet.setData(buffer);
socket.receive(packet);
String r = new String(packet.getData()).trim();
System.out.println("Step 3");
return r.equals("Ok");
}
private void sendFile() throws IOException {
buffer = new byte[(int) fileLength];
try (FileInputStream fis = new FileInputStream(fileName)) {
int s = fis.read(buffer);
}
packet.setData(buffer);
socket.send(packet);
System.out.println("Step 4");
}
}
Loading…
Cancel
Save