Nätverksprogrammering. Hugo Quisbert Nätverk

Similar documents
Network Programming using sockets. Distributed Software Systems Prof. Sanjeev Setia

Lesson: All About Sockets

Socket Programming in Java

Network Communication

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Creating a Simple, Multithreaded Chat System with Java

SSC - Communication and Networking Java Socket Programming (II)

Application Development with TCP/IP. Brian S. Mitchell Drexel University

NETWORK PROGRAMMING IN JAVA USING SOCKETS

Penetration from application down to OS

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

Tutorial c-treeace Web Service Using Java

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Network Programming using sockets

Socket Programming. Announcement. Lectures moved to

Data Communication & Networks G

Java Network. Slides prepared by : Farzana Rahman

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets

Building a Multi-Threaded Web Server

Java Servlet Tutorial. Java Servlet Tutorial

Java Programming: Sockets in Java

Socket-based Network Communication in J2SE and J2ME

Principles and Techniques of DBMS 5 Servlet

Division of Informatics, University of Edinburgh

Communicating with a Barco projector over network. Technical note

Mail User Agent Project

Implementing the Shop with EJB

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Network/Socket Programming in Java. Rajkumar Buyya

Socket Programming. A er learning the contents of this chapter, the reader will be able to:

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Advanced Network Programming Lab using Java. Angelos Stavrou

B.Sc (Honours) - Software Development

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers

Configure a SOAScheduler for a composite in SOA Suite 11g. By Robert Baumgartner, Senior Solution Architect ORACLE

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

Assignment 4 Solutions

PA165 - Lab session - Web Presentation Layer

Network-based Applications. Pavani Diwanji David Brown JavaSoft

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

ExempleRMI.java. // Fichier de defintion des droits et proprietes // System.setProperty("java.security.policy","../server.java.

Web Application Programmer's Guide

2. Follow the installation directions and install the server on ccc

WebSphere and Message Driven Beans

An introduction to web programming with Java

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

!"# $ %!&' # &! ())*!$

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

Brazil + JDBC Juin 2001, douin@cnam.fr

An Overview of Java. overview-1

CISC 4700 L01 Network & Client- Server Programming Spring Harold, Chapter 8: Sockets for Clients

Capario B2B EDI Transaction Connection. Technical Specification for B2B Clients

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, Java Servlets

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

An Android-based Instant Message Application

Manual. Programmer's Guide for Java API

Consuming a Web Service(SOAP and RESTful) in Java. Cheat Sheet For Consuming Services in Java

CS/CE 2336 Computer Science II

JAVA Program For Processing SMS Messages

Different types of resources are specified by their scheme, each different pattern is implemented by a specific protocol:

Übungen zu Kommunikationssysteme Multicast

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

The Java Series Network and WWW Programming Servlets. The Java Series. Network and WWW Programming Raul RAMOS / CERN-IT User Support Slide 1

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

Web Programming: Announcements. Sara Sprenkle August 3, August 3, Assignment 6 due today Project 2 due next Wednesday Review XML

ACI Commerce Gateway Hosted Payment Page Guide

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

When the transport layer tries to establish a connection with the server, it is blocked by the firewall. When this happens, the RMI transport layer

Agenda. Network Programming and Java Sockets. Introduction. Internet Applications Serving Local and Remote Users

JAVA - FILES AND I/O

2.8. Session management

gomobi Traffic Switching Guide Version 0.9, 28 September 2010

JDBC (Java / SQL Programming) CS 377: Database Systems

WRITING DATA TO A BINARY FILE

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Lecture J - Exceptions

Introduktion til distribuerede systemer uge 37 - fil og webserver

Socket programming. Complement for the programming assignment INFO-0010

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

public static void main(string[] args) { System.out.println("hello, world"); } }

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

What is an I/O Stream?

How to use JavaMail to send

Course Intro Instructor Intro Java Intro, Continued

DATABASDESIGN FÖR INGENJÖRER - 1DL124

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

Projektet Computer: Specifikation. Objektorienterad modellering och diskreta strukturer / design. Projektet Computer: Data. Projektet Computer: Test

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

Prof. Edwar Saliba Júnior

Brekeke PBX Web Service

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Transcription:

Nätverksprogrammering Hugo Quisbert 20130226 1 Nätverk 2 1

Nätverk Definition: TCP (Transport Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers. Definition: UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP. 3 Java - Nätverksprogrammering nätverk är Javas själ nätverksbaserade applikationer java.net klasser för kommunikation och åtkomst av nätverksresurser 4 2

Java - Nätverksprogrammering TCP-baserade klasser: URL URLConnection Socket ServerSocket UDP- baserade klasser: DatagramPacket DatagramSocket, och MulticastSocket 5 Java- nätverksklasser Dessa klasser indelas i två kategorier: URLs Uniform Resource Locator Sockets API (Application Program Interface) åtkomst nätverksprotokoll 6 3

Java -URL En URL refererar till någon maskin (server) i ett nätverk (Internet) http://www.java.sun http://www.liu.se http: protokoll identifierare www.java.sun: resursnamn www.liu.se: resursnamn 7 Java -URL I ett Javaprogram kan man skapa ett objekt av klassen URL URL gamelan = new URL("http://www.gamelan.com"); en resurs kan vara: en mapp en fil en databasfråga 8 4

Java -URL URL aurl = new URL( http://java.sun.com:80/tutorial/ intro.html#downloading ); protocoll = http host = java.sun.com port = 80 [path/]filenamn = tutorial/intro.html ref = DOWNLOADING 9 10 5

Sockets Definition: A socketis one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Hugo Quisbert 11 Sockets Hugo Quisbert 12 6

Datagram import java.io.*; public class QuoteServer { public static void main(string[] args) throws IOException { new QuoteServerThread().start(); 13 import java.io.*; import java.net.*; import java.util.*; public class QuoteServerThread extends Thread { protected DatagramSocket socket = null; protected BufferedReader in = null; protected boolean morequotes = true; public QuoteServerThread() throws IOException { this("quoteserverthread"); public QuoteServerThread(String name) throws IOException { super(name); socket = new DatagramSocket(4445); try { in = new BufferedReader(new FileReader("one-liners.txt")); catch (FileNotFoundException e) { System.err.println("Could not open quote file. Serving time instead."); 14 7

datagram public void run() { while (morequotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // figure out response String dstring = null; if (in == null) dstring = new Date().toString(); else dstring = getnextquote(); buf = dstring.getbytes(); ----> 15 datagram // send the response to the client at "address" and "port" InetAddress address = packet.getaddress(); int port = packet.getport(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); catch (IOException e) { e.printstacktrace(); morequotes = false; socket.close(); 16 8

Datagram protected String getnextquote() { String returnvalue = null; try { if ((returnvalue = in.readline()) == null) { in.close(); morequotes = false; returnvalue = "No more quotes. Goodbye."; catch (IOException e) { returnvalue = "IOException occurred in server."; return returnvalue; 17 Datagram import java.io.*; import java.net.*; import java.util.*; public class QuoteClient { public static void main(string[] args) throws IOException { if (args.length!= 1) { System.out.println("Usage: java QuoteClient <hostname>"); return; // get a datagram socket DatagramSocket socket = new DatagramSocket(); 18 9

Datagram // send request byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName(args[0]); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData(), 0, packet.getlength()); System.out.println("Quote of the Moment: " + received); socket.close(); 19 Servelt med DB Access import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; public class DBServlet extends HttpServlet { protected void processrequest(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); String[][] dat; try { /* TODO output your page here. You may use following sample code. */ out.println("<html>"); out.println("<head>"); out.println("<title>servlet DBServlet</title>"); out.println("</head>"); out.println("<body>"); 20 10

Dervelt med DB Access out.println("<h1>servlet DBServlet at " + request.getcontextpath() + "</h1>"); DBAccess dbac = new DBAccess(); dat = dbac.getdata(); out.print(tohtmltable.totable(dat)); out.println("</body>"); out.println("</html>"); finally { out.close(); 21 import java.sql.*; public class DBAccess { static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DATABASE_URL = "jdbc:mysql://localhost/mydb?" + "user=hugo_q&password=admin"; private java.sql.connection connection; private java.sql.statement statement; public String[][] getdata(){ String[][] results = new String[6][4]; try{ Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DATABASE_URL); statement = connection.createstatement(); ResultSet resultset = statement.executequery( "SELECT * FROM kund"); resultset.getrow(); int i = 0; results[i][0] = "Namn"; results[i][1] = "Adress"; results[i][2] = "Tel"; results[i][3] = "E-post"; 22 11

while(resultset.next()){ //results[++i][j] = resultset.getstring("namn") + " " + resultset.getstring("adress") + " " + resultset.getstring("tel_nr") + " " + resultset.getstring("epost"); i++; results[i][0] = resultset.getstring("namn"); results[i][1] = resultset.getstring("adress"); results[i][2] = resultset.getstring("tel_nr"); results[i][3] = resultset.getstring("epost"); for(int k = 0; k < 6; k++){ for(int j = 0; j < 4; j++){ System.out.print(results[k][j].toString() + " "); statement.close(); connection.close(); System.out.println("Lots of data retrieved"); catch(classnotfoundexception cnfe){system.out.println(cnfe.tostring()); catch(sqlexception sqle){system.out.println(sqle.tostring()); return results; 23 public class ToHTMLTable { public static String totable(string[][] data){ StringBuilder html = new StringBuilder("<table>"); for(string elem:data[0]){ html.append("<th>").append(elem.tostring()).append("</th>"); for(int i = 1; i < data.length; i++){ String[] row = data[i]; html.append("<tr>"); for(string elem:row){ html.append("<td>").append(elem.tostring()).append("</td>"); html.append("</tr>"); html.append("</table>"); return html.tostring(); 24 12