1 / 32

Network programming

Network programming. network programming… java.net.*; client/server programming… tcp/ip – packet, udp – datagram jdbc (java.sql.*) rmi servlet. port, socket, connection…. WhoAmI. import java.net.*; public class WhoAmI { public static void main(String[] args) {

kennethlee
Télécharger la présentation

Network programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Network programming • network programming… java.net.*; • client/server programming… • tcp/ip – packet, udp – datagram • jdbc (java.sql.*) • rmi • servlet

  2. port, socket, connection…

  3. WhoAmI import java.net.*; public class WhoAmI { public static void main(String[] args) { if(args.length != 1) { System.err.println("Usage: WhoAmI MachineName"); System.exit(1); } try { InetAddress a = InetAddress.getByName(args[0]); System.out.println(a); } catch (Exception e) { System.out.println("can not locate:" + args[0]); } } } java WhoAmI www.sme.sk www.sme.sk/217.67.20.187

  4. Google.com import java.net.*; class Google { public static void main (String args[]) { try { InetAddress[] addresses = InetAddress.getAllByName("www.google.com"); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } } catch (UnknownHostException e) { System.out.println("Could not find www.google.com"); } } } java Google www.google.com/209.85.129.147 www.google.com/209.85.129.99 www.google.com/209.85.129.104

  5. localhost try { InetAddress iaddress = InetAddress.getLocalHost(); System.out.println(iaddress); System.out.println("Hello. My name is " + iaddress.getHostName()); byte[] address = iaddress.getAddress(); System.out.print("My address is "); for (int i = 0; i < address.length; i++) { int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i]; System.out.print(unsignedByte + "."); } System.out.println(); } catch (UnknownHostException e) { System.out.println("Could not find this computer's address."); } java Localhost nod68/192.168.1.12 Hello. My name is nod68 My address is 192.168.1.12.

  6. Port Scanner import java.net.*; import java.io.IOException; import javax.swing.*; public class PortScanner { public static void main(String[] args) { InetAddress ia=null; String host=null; try { host=JOptionPane.showInputDialog("Enter the Host name to scan:"); if(host!=null){ ia = InetAddress.getByName(host); String hostname = ia.getHostName(); for (int port = 0; port < 65536; port++) try { Socket s = new Socket(ia,port); System.out.println("Server is listening on port " + port+ " of " + hostname); s.close(); } catch (IOException ex) { System.out.println("Server is not listening on port " + port+ " of " + hostname); } } } catch (UnknownHostException e) { System.err.println(e ); } } } Server is listening on port 22 of danka.ii.fmph.uniba.sk Server is listening on port 23 of danka.ii.fmph.uniba.sk Server is not listening on port 24 of danka.ii.fmph.uniba.sk Server is listening on port 25 of danka.ii.fmph.uniba.sk Server is not listening on port 26 of danka.ii.fmph.uniba.sk Server is not listening on port 27 of danka.ii.fmph.uniba.sk

  7. Server import java.io.*; import java.net.*; public class JabberServer { public static final int PORT = 8080; public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Started: " + s); try { Socket socket = s.accept(); try { System.out.println("Connection accepted: "+ socket); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); while (true) { String str = in.readLine(); if (str.equals("END")) break; System.out.println("Echoing: " + str); out.println(str); } } finally { System.out.println("closing..."); socket.close(); } } finally { s.close(); } } } java JabberServer Started: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=8080] Connection accepted: Socket[addr=/127.0.0.1,port=1075,localport=8080] Echoing: howdy 0 Echoing: howdy 1 Echoing: howdy 2 Echoing: howdy 3 Echoing: howdy 4 Echoing: howdy 5 Echoing: howdy 6 Echoing: howdy 7 Echoing: howdy 8 Echoing: howdy 9 closing...

  8. Client import java.net.*; import java.io.*; public class JabberClient { public static void main(String[] args) throws IOException { InetAddress addr = InetAddress.getByName(null); // InetAddress addr = InetAddress.getByName("127.0.0.1"); // InetAddress addr = InetAddress.getByName("localhost"); System.out.println("addr = " + addr); Socket socket = new Socket(addr, JabberServer.PORT); try { System.out.println("socket = " + socket); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); for(int i = 0; i < 10; i ++) { out.println("howdy " + i); String str = in.readLine(); System.out.println(str); } out.println("END"); } finally { System.out.println("closing..."); socket.close(); } } } java JabberClient addr = localhost/127.0.0.1 socket = Socket[addr=localhost/127.0.0.1,port=8080,localport=1075] howdy 0 howdy 1 howdy 2 howdy 3 howdy 4 howdy 5 howdy 6 howdy 7 howdy 8 howdy 9 closing...

  9. DateServer import java.net.*; import java.io.*; import java.util.Date; public class DateServer { static final int LISTENING_PORT = 32007; public static void main(String[] args) { ServerSocket listener; Socket connection; try { listener = new ServerSocket(LISTENING_PORT); while (true) { connection = listener.accept(); sendDate(connection); } } catch (Exception e) { System.out.println("Error: " + e); return; } } static void sendDate(Socket client) { try { System.out.println("Connection from " + client.getInetAddress().toString() ); Date now = new Date(); PrintWriter outgoing = new PrintWriter( client.getOutputStream() ); outgoing.println( now.toString() ); outgoing.flush(); client.close(); } catch (Exception e){ System.out.println("Error: " + e); } } }

  10. DateClient import java.net.*; import java.io.*; public class DateClient { static final int LISTENING_PORT = 32007; public static void main(String[] args) { String computer; Socket connection; Reader incoming; if (args.length > 0) computer = args[0]; else { System.out.println( "Usage: java DateClient <server>"); return; } try { connection = new Socket( computer, LISTENING_PORT ); incoming = new InputStreamReader( connection.getInputStream() ); while (true) { int ch = incoming.read(); if (ch == -1 || ch == '\n' || ch == '\r') break; System.out.print( (char)ch ); } System.out.println(); incoming.close(); } catch (Exception e) { System.out.println("Error: " + e); } } } Listening on port 32007 Connection from /127.0.0.1 Connection from /127.0.0.1 Connection from /127.0.0.1 java DateClient localhost Sat Dec 02 20:57:09 CET 2006 java DateClient localhost Sat Dec 02 20:57:11 CET 2006

  11. read, write socket Text • BufferedReader is = new BufferedReader (newInputStreamReader(sock.getInputStream())); • PrintWriter os = new PrintWriter(sock.getOutputStream(), true); Binárne dáta • DataInputStream is = new DataInputStream(sock.getInputStream()); • DataOutputStream os = new DataOutputStream(sock.getOutputStream()); Veľké binárne dáta • DataInputStream is = new DataInputStream(new BufferedInputStream(sock.getInputStream())); • DataOutputStream os = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));

  12. MultiServer import java.io.*; import java.net.*; public class MultiJabberServer { static final int PORT = 4321; public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Server Started"); try { while(true) { Socket socket = s.accept(); try { new ServeOneJabber(socket); } catch(IOException e) { socket.close(); } } } finally { s.close(); } } } class ServeOneJabber extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; public ServeOneJabber(Socket s) throws IOException { socket = s; in = new BufferedReader(new InputStreamReader( socket.getInputStream())); out = new PrintWriter(new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); start(); } public void run() { try { while (true) { String str = in.readLine(); if (str.equals("END")) break; System.out.println("Echoing: " + str); out.println(str); } System.out.println("closing..."); } catch (IOException e) { } finally { try { socket.close(); } catch(IOException e) {} } } }

  13. public void run() { try { for(int i = 0; i < 25; i++) { out.println("Client " + id + ": " + i); String str = in.readLine(); System.out.println(str); } out.println("END"); } catch(IOException e) { } finally { try { socket.close(); } catch(IOException e) {} threadcount--; } } } MultiClient import java.net.*; import java.io.*; class JabberClientThread extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; private static int counter = 0; private int id = counter++; private static int threadcount = 0; public static int threadCount() { return threadcount; } public JabberClientThread(InetAddress addr) { System.out.println("Making client " + id); threadcount++; try { socket = new Socket(addr, MultiJabberServer.PORT); } catch(IOException e) { } try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); start(); } catch(IOException e) { try { socket.close(); } catch(IOException e2) {} } }

  14. MultiClient import java.io.*; import java.net.*; public class MultiJabberClient { static final int MAX_THREADS = 40; public static void main(String[] args) throws IOException, InterruptedException { InetAddress addr = InetAddress.getByName(null); while(true) { if(JabberClientThread.threadCount() < MAX_THREADS) new JabberClientThread(addr); Thread.currentThread().sleep(100); } } }

  15. MultiClient

  16. Chat

  17. handshake try { listener = new ServerSocket(port); System.out.println("Listening on port " + listener.getLocalPort()); connection = listener.accept(); listener.close(); incoming = new BufferedReader(new InputStreamReader(connection.getInputStream())); outgoing = new PrintWriter(connection.getOutputStream()); outgoing.println(HANDSHAKE); outgoing.flush(); messageIn = incoming.readLine(); if (! messageIn.equals(HANDSHAKE) ) { throw new IOException("Connected program is not Chat!"); } System.out.println("Connected. Waiting...\n"); } catch (Exception e) { System.out.println("An error occurred while opening connection."); System.out.println(e.toString()); return; }

  18. Chat server try { while (true) { System.out.println("WAITING..."); messageIn = incoming.readLine(); if (messageIn.length() > 0) { if (messageIn.charAt(0) == CLOSE) { System.out.println("Connection closed at other end."); connection.close(); break; } messageIn = messageIn.substring(1); } System.out.println("RECEIVED: " + messageIn); System.out.print("=>"); messageOut = bufIn.readLine(); if (messageOut.equalsIgnoreCase("quit")) { outgoing.println(CLOSE); outgoing.flush(); connection.close(); System.out.println("Connection closed."); break; } outgoing.println(MESSAGE + messageOut); outgoing.flush(); if (outgoing.checkError()) { throw new IOException("Error ocurred while reading incoming message."); } } } catch (Exception e) {

  19. Chat client try { while (true) { System.out.print("->"); messageOut = bufIn.readLine(); if (messageOut.equalsIgnoreCase("quit")) { outgoing.println(CLOSE); outgoing.flush(); connection.close(); System.out.println("Connection closed."); break; } outgoing.println(MESSAGE + messageOut); outgoing.flush(); if (outgoing.checkError()) { throw new IOException("Error ocurred while reading incoming message."); } System.out.println("WAITING..."); messageIn = incoming.readLine(); if (messageIn.length() > 0) { if (messageIn.charAt(0) == CLOSE) { System.out.println("Connection closed at other end."); connection.close(); break; } messageIn = messageIn.substring(1); } System.out.println("RECEIVED: " + messageIn); } }

  20. miniHTTPServer import java.net.*; import java.io.*; import java.util.*; try { // cache the file theFile = new FileInputStream(args[0]); DataInputStream dis = new DataInputStream(theFile); if (args[0].endsWith(".html") || args[0].endsWith(".htm")) ContentType = "text/html"; else ContentType = "text/plain"; try { String thisLine = ""; while ((thisLine = dis.readLine()) != null) theData += thisLine + "\n"; } catch (Exception e) { System.err.println("Error: " + e); } } catch (Exception e) { System.err.println(e); System.err.println( "Usage: java miniHTTPServer filename port"); System.exit(1); } java miniHTTPServer tabulka.txt 1234 Accepting connections on port 1234 Data to be sent: 81-100 A 67-80 B 53-66 C 39-52 D 25-38 E 0-24 Fx java miniHTTPServer index.html 1234

  21. miniHTTPServer while (true) { miniHTTPServer fs = new miniHTTPServer(ss.accept()); fs.start(); } public void run() { try { PrintStream os = new PrintStream(theConnection.getOutputStream()); DataInputStream is = new DataInputStream(theConnection.getInputStream()); String request = is.readLine(); if (request.indexOf("HTTP/") != -1) { while (true) { String thisLine = is.readLine(); if (thisLine.trim().equals("")) break; } os.print("HTTP/1.0 200 OK\r\n"); Date now = new Date(); os.print("Date: " + now + "\r\n"); os.print("Server: OneFile 1.0\r\n"); os.print("Content-length: " + theData.length() + "\r\n"); os.print("Content-type: " + ContentType + "\r\n\r\n"); } os.println(theData); theConnection.close(); } catch (IOException e) { } } }

  22. Nonblocking import java.net.*; import java.io.*; import java.nio.channels.SocketChannel; public class NonBlock { public static void main(String args[]) throws IOException { try { String hostName = "www.sme.sk"; int port = 80; // Create a non-blocking socket channel SocketChannel sChannel = SocketChannel.open(); sChannel.configureBlocking(false); // Send a connection request to the server; this method is non-blocking sChannel.connect(new InetSocketAddress(hostName, port)); int i=0; while (!sChannel.finishConnect()) { System.out.println(i++ + ":" + sChannel.isConnected()); } System.out.println(sChannel.isConnected()); } catch (IOException e) { System.out.println(e.getMessage()); } } } java NonBlock 0:false 1:false 2:false 3:false 4:false 5:false true

  23. jdbc import java.sql.*; public class Lookup { public static void main(String[] args) { String dbUrl = "jdbc:odbc:radmon"; String user = ""; String password = ""; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection(dbUrl, user, password); Statement s = c.createStatement(); ResultSet r = s.executeQuery( "SELECT nazov,ulica,mesto,kraj FROM radmon.stanica " + "WHERE (kraj='" + args[0] + "') " + " AND (Ulica Is Not Null) " + "ORDER BY mesto"); while(r.next()) { System.out.println( r.getString("kraj") + ", " + r.getString("mesto") + ": " + r.getString("ulica") + ": " + r.getString("nazov") ); } s.close(); } catch(Exception e) { e.printStackTrace(); } } } java Lookup "Banska Bystrica" Banska Bystrica, Banska Bystrica: Nßm. Csl. armßdy: OU v B.Bystrici Banska Bystrica, Banska Bystrica: Namestie L. Stura: KU v B.Bystrici Banska Bystrica, Brezno: Razusova: OU v Brezne Banska Bystrica, Detva: Zahradna: OU v Detve Banska Bystrica, Krupina: Priemyselna: OU v Krupine Banska Bystrica, Lucenec: Nam. Republiky: OU v Lucenci Banska Bystrica, Rimavska Sobota: Nam. M.Tompu: OU v Rimavskej Sobote Banska Bystrica, Slovenska Lupca: Postovy priecinok: KCHL v Sl.Lupci Banska Bystrica, Velky Krtis: Madacha: OU vo Velkom Krtisi

  24. class SearchForL implements TextListener { public void textValueChanged(TextEvent te) { ResultSet r; if(searchFor.getText().length() == 0) { completion.setText(""); results.setText(""); return; } try { r = s.executeQuery( "SELECT nazov,ulica,mesto,kraj FROM radmon.stanica " + "WHERE (kraj='" + searchFor.getText() + "') “ + " AND (Ulica Is Not Null) ORDER BY mesto"); if(r.next()) completion.setText(r.getString("kraj")); r = s.executeQuery( "SELECT nazov,ulica,mesto,kraj FROM radmon.stanica " + "WHERE (kraj='" + searchFor.getText() + "') “ + " AND (Ulica Is Not Null) ORDER BY mesto"); } catch(Exception e) { results.setText(searchFor.getText() + "\n"); results.append(e.getMessage()); return; } results.setText(""); try { while(r.next()) { results.append(r.getString("kraj") + ", " + r.getString("mesto") + ": " + r.getString("ulica") + ": " + r.getString("nazov") + "\n"); } } catch(Exception e) { results.setText(e.getMessage()); } } } jdbc & gui

  25. Insert image private void insPicture(Connection c, String name, String fName) { try { File f = new File(fName); FileInputStream in = new FileInputStream(f); byte[] image = new byte[(int) f.length()]; in.read(image); String sql = "INSERT INTO testImage VALUES(?,?)"; PreparedStatement stmt = c.prepareStatement(sql); stmt.setString(1, name); stmt.setBytes(2, image); stmt.executeUpdate(); stmt.close(); } catch (Exception e) { System.out.print(e.getMessage()); } }

  26. Call stored proc FOO try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:test1","sa","password"); String sql= "{ call FOO(?) }"; cst=con.prepareCall(sql); int i=1; cst.registerOutParameter(1,Types.NUMERIC,0); cst.setInt(1,i); cst.executeUpdate(); i=cst.getInt(1); } catch(Exception proc) { System.out.println("error ine executed query is :" + proc); }

  27. RMI RMIClient1.java: Client program that calls the sendData method on the RemoteServer server object. RMIClient2.java: Client program that calls the getData method on the RemoteServer server object. RemoteServer.java: Remote server object that implements Send.java and the sendData and getData remote methods. Send.java: Remote interface that declares the sendData and getData remote server methods.

  28. RemoteServer public interface Send extends Remote { public void sendData(String text) throws RemoteException; public String getData() throws RemoteException; } class RemoteServer extends UnicastRemoteObject implements Send { String text; public RemoteServer() throws RemoteException { super(); } public void sendData(String gotText){ text = gotText; } public String getData(){ return text; } public static void main(String[] args){ if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } String name = “//server/Send"; try { Send remoteServer = new RemoteServer(); Naming.rebind(name, remoteServer); System.out.println("RemoteServer bound"); } catch (java.rmi.RemoteException e) { System.out.println("Cannot create remote server object"); } catch (java.net.MalformedURLException e) { System.out.println("Cannot look up server object"); } }

  29. RemoteClient1 public void actionPerformed(ActionEvent event){ Object source = event.getSource(); if(source == button){ String text = textField.getText(); try{ send.sendData(text); } catch (java.rmi.RemoteException e) { System.out.println( "Cannot send data to server"); } textField.setText(new String("")); } } RMIClient1 frame = new RMIClient1(); if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { //args[0] contains name of server where Send runs String name = "//" + args[0] + "/Send"; send = ((Send) Naming.lookup(name)); } catch (java.rmi.NotBoundException e) { System.out.println("Cannot look up remote server object"); } catch(java.rmi.RemoteException e){ System.out.println("Cannot look up remote server object"); } catch(java.net.MalformedURLException e) { System.out.println("Cannot look up remote server object");

  30. RemoteClient2 public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source == button){ try{ String text = send.getData(); textArea.append(text); } catch (java.rmi.RemoteException e) { System.out.println("Cannot send data to server"); } } } } RMIClient2 frame = new RMIClient2(); if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { String name = "//" + args[0] + "/Send"; send = ((Send) Naming.lookup(name)); } catch (java.rmi.NotBoundException e) { System.out.println("Cannot look up remote server object"); } catch(java.rmi.RemoteException e){ System.out.println("Cannot look up remote server object"); } catch(java.net.MalformedURLException e) { System.out.println("Cannot look up remote server object"); }

  31. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ExampServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>Example</title>" + "<body bgcolor=FFFFFF>"); out.println("<h2>Button Clicked</h2>"); String DATA = request.getParameter("DATA"); if(DATA != null){ out.println(DATA); } else { out.println("No text entered."); } out.println("<P>Return to <A HREF="../simpleHTML.html">Form</A>"); out.close(); } } Servlet

  32. paradigmy for(int i=1; i<args.length; i++) http://ii.fmph.uniba.sk/~borovan/PARA/index.html

More Related