| 1 | import java.io.*; |
| 2 | import java.net.*; |
| 3 | |
| 4 | class PongNetwork { |
| 5 | boolean startServer(int port) { |
| 6 | try { |
| 7 | ServerSocket ss = new ServerSocket(port); |
| 8 | //while (true) { |
| 9 | final Socket sock = ss.accept(); |
| 10 | InputStream is = sock.getInputStream(); |
| 11 | OutputStream os = sock.getOutputStream(); |
| 12 | |
| 13 | BufferedReader br = new BufferedReader(new InputStreamReader(is)); |
| 14 | |
| 15 | String s = ""; |
| 16 | while (s != null) { |
| 17 | s = br.readLine(); |
| 18 | if (s != null) |
| 19 | System.out.println(s); |
| 20 | } |
| 21 | |
| 22 | sock.close(); |
| 23 | //} |
| 24 | } catch(Exception e) { |
| 25 | e.printStackTrace(); |
| 26 | return false; |
| 27 | } |
| 28 | return true; |
| 29 | } |
| 30 | |
| 31 | boolean startClient(int port) { |
| 32 | try { |
| 33 | System.out.println("Connecting..."); |
| 34 | Socket sc = new Socket(); |
| 35 | sc.connect(new InetSocketAddress("localhost", port), 2000); |
| 36 | |
| 37 | System.out.println("Connected!"); |
| 38 | |
| 39 | BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream())); |
| 40 | BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream())); |
| 41 | |
| 42 | bw.write("GET /\n\n"); // zapíšeme předem připravený požadavek |
| 43 | bw.flush(); // odeslání z bufferu |
| 44 | |
| 45 | String line = ""; |
| 46 | |
| 47 | // dokud jsou data, opakuj |
| 48 | while (line != null) { |
| 49 | line = br.readLine(); |
| 50 | if (line != null) System.out.println(line); // platná data vypisuj |
| 51 | } |
| 52 | |
| 53 | sc.close(); // zavření socketu |
| 54 | |
| 55 | } catch (Exception e) { |
| 56 | //e.printStackTrace(); |
| 57 | System.out.println("Could not connect!"); |
| 58 | return false; |
| 59 | } |
| 60 | return true; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | class socket { |
| 65 | public static void main(String[] args) { |
| 66 | PongNetwork pn = new PongNetwork(); |
| 67 | if(!pn.startClient(1033)) pn.startServer(1033); |
| 68 | } |
| 69 | } |