Network Communication and Services

download Network Communication and Services

of 47

Transcript of Network Communication and Services

  • 8/16/2019 Network Communication and Services

    1/47

    4. Network communication andservices

    This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To viewa cop o! this license" visithttp#$$creativecommons.or%$licenses$b-nc-sa$4.0$ 

    Service and Process Programming

     Arturo &ernal

    Nacho Iborra

    I'S San (icente

    http://creativecommons.org/licenses/by-nc-sa/4.0/http://creativecommons.org/licenses/by-nc-sa/4.0/

  • 8/16/2019 Network Communication and Services

    2/47

    Table of Contents

    4. Network communication and services

    ). Introduction....................................................................................................................*

    1.1. Introduction to sockets...........................................................................................31.2. Client-server communication.................................................................................31.3. Socket types...........................................................................................................4

    +. &asic usa%e o! ,ava sockets.........................................................................................2.1. Using TCP sockets................................................................................................. 2.2. Using U!P sockets................................................................................................"2.3. #ore a$out t%e Inet&ddress class.......................................................................12 2.4. Connecting multiple clients. Sockets and t%reads...............................................12 

    *. Some special connections...........................................................................................)3.1. #ulticast sockets..................................................................................................1 3.2. '$(ect seriali)ation...............................................................................................1* 

    4. T/ and ST/ client...................................................................................................+04.1 +TP Client.............................................................................................................2, 4.2 S#TP Client..........................................................................................................23

    . 1TT/2S3 and eb Services........................................................................................+.1 'pening and reading a TTP connection.............................................................2 .2 asic /e$ Service access....................................................................................20 .3 S' processing..................................................................................................20 .4 &ccessing e$ services rom a dierent t%read...................................................31. 56T7 P'ST7 PUT7 !686T6...................................................................................33.* 6mulating an &&9 call.........................................................................................44

    .: #aintaining session it% cookies..........................................................................44.: Sending iles..........................................................................................................4* 

    Service and Process Programming ; etork communication and services 2 

  • 8/16/2019 Network Communication and Services

    3/47

    1. Introduction

    In this unit we are %oin% to !ocus on how applications communicate throu%h a network2either a local network or the Internet3. e will read about some low-level communication

    techni5ues and some other hi%h-level services.irst" we are %oin% to see how to communicate two ,ava applications throu%h a network busin% sockets. e will see what a socket is" what tpes o! sockets we can use and how touse them.

    Then" we will e6plain some hi%her level network services" such as e-mail" !tp access or web services" and how to deal with them in ,ava.

    In addition to this" we will e6plain some secure pro%rammin% techni5ues" in order toauthenticate in a remote server" or encrpt the in!ormation that we send throu%h thenetwork.

    1.1. Introduction to sockets A socket is a communication sstem between processes runnin% on di!!erent machines ina network. These processes send and receive in!ormation throu%h a connector" and thisconnector is commonl called socket .

    1.1.1. Sockets and port numbers

    'ach socket has a port number  associated to it. This number identi!ies the process that issendin% or receivin% the in!ormation throu%h this socket. So" when a local process wantsto communicate with a remote process" the both establish their own port numbers" andwhenever the in!ormation is sent to each other" the computer knows which process mustreceive it b checkin% the destination port.

    +or instance7 i a mac%ine & %as a process P& listening on port 3,7 and a mac%ine %as anot%er process P listening on port 447 %enever a message gets tomac%ine indicating port num$er 447 t%en t%is message ill $e received $y  process P

  • 8/16/2019 Network Communication and Services

    4/47

    e have said be!ore that both sides need to have a port number associated to theconnection. The port number o! the server must be known 2!or instance" port 80 !or webcommunications" or port +) !or T/ access3" but the client port number is randomlassi%ned" so that the server will be able to send its responses to the client.

    +or instance7 i e try to create a connection to a e$ server %osted in.myserver.com7 e ill set port 0, as our destination port. T%en7 t%e server ill 

    accept our connection7 and automatically a random port num$er

  • 8/16/2019 Network Communication and Services

    5/47

    !. "asic usage of #ava sockets

    In this section we are %oin% to learn how to deal with the two main tpes o! sockets 2TC/and 9:/3 in ,ava. The core o! ,ava sockets is de!ined in the  $ava.net packa%e. There" we

    can !ind some use!ul classes" as we will see now.

    2.1. Using TCP sockets

    I! we want to work with TC/ sockets" we will need to handle these two classes#

    • ServerSocket class" that will be used to implement a socket in the server side" that

    will be listenin% to client connection re5uests.

    • Socket class" that will hold the communication between both sides. e will use a

    Socket  ob;ect in each side.

    In order to connect a client to a server" we will !ollow these steps#

    In the server side#

    ). Create a ServerSocket  ob;ect in the server" speci!in% the desired port number.

  • 8/16/2019 Network Communication and Services

    6/47

    ). Create a Socket  ob;ect with the server address and port.

    +. hen this instruction is completed" we have our connection to the server read"althou%h it ma throw an e6ception i! somethin% %oes wron%.

    *. Then" we can also create input and$or output streams to send or receive datato$!rom the server.

    I! we put all o! this to%ether in a piece o! code#try (

    Socket m"Socket = new Socket($a%%ress$& portNumber);DataInputStream sIn = new DataInputStream(m"Socket.getInputStream());DataOutputStream sOut = new DataOutputStream(m"Socket.getOutputStream());

    ){

    ... // Communication process} catch (IO!ception e) {

    S"stem.out.print#n(e);}

    !.1.1. %&ampleLet=s implement our !irst" complete e6ample. henever we create a client-server application" we normall create two separate pro;ects# one !or the server and another one!or the client" so that we can distribute both sides o! the application separatel. In thiscase" we are %oin% to create a client that sas >1ello> to server" and a server that" whenreceives this messa%e" sends an answer with >?oodbe> to the client.

    In the client side" our code should look like this#

    public class 'reetC#ient{  public static void main(String* args)

    {  try (

    Socket m"Socket = new Socket($#oca#+ost$& ,---);DataInputStream socketIn =

    new DataInputStream(m"Socket.getInputStream());  DataOutputStream socketOut =

    new DataOutputStream(m"Socket.getOutputStream());  )  {

    socketOut.rite01($2e##o$);  String response = socketIn.rea%01();  S"stem.out.print#n($3eceive%4 $ 5 response);

      } catch (IO!ception e) {  S"stem.out.print#n(e);  }  }}

    In the server side" the code is#

    public class 'reetServer{  public static void main(String* args)

    {  try (

      ServerSocket server =new

     ServerSocket(,---);  Socket service = server.accept();

    Service and Process Programming ; etork communication and services * 

  • 8/16/2019 Network Communication and Services

    7/47

      DataInputStream socketIn =new DataInputStream(service.getInputStream());

      DataOutputStream socketOut =new DataOutputStream(service.getOutputStream());

      )  {

    // 3ea% t+e message 6rom t+e c#ient

      String message = socketIn.rea%01();  // 7rint t+e message  S"stem.out.print#n($3eceive%4 $ 5 message);  // 8nser goo%b"e to t+e c#ient  socketOut.rite01($'oo%b"e$); 

    } catch (IO!ception e) {  S"stem.out.print#n(e);  }  }}

    I! we want to run this e6ample 2or an other client-server application3" we must start b

    runnin% the server" and when it=s waitin% !or connections" then we run the client. Theoutput should be the te6t > in the server console" and the te6t > in the client console.

    !.1.!. Some implementation issues

    I! we take a look at previous e6amples#

    • Note that we have used a !ataInputStream  ob;ect !or readin% and a

    !ata'utputStream ob;ect !or writin%. e could use other ob;ects !or readin% or writin%" such as uered?eader  or PrintStream. ith these two ob;ects" we couldsend and receive te6t messa%es line b line" instead o! usin% 9T strin%s.

    • I! the communication between client and server is not snchronous 2i.e." the clientcan send messa%es to the server at an time and$or there are multiple clientscommunicatin% with server at an time3" we will need to open the connections2socket" input and$or output streams3 inside the try  clause 2not inside the try-it%-resource clause3" and close them in a inally  clause. e will see an e6ample o! thiswhen usin% threads to deal with multiple connections 2section +.43.

      try (ServerSocket server = new ServerSocket(,---))  {  service = ...

    socketIn = ...  socketOut = ...

      ...  } catch (IO!ception e) {  S"stem.out.print#n(e);  } finally {  try {  if (socketOut 9= null)  socketOut.c#ose();  } catch (IO!ception e!) {}  try {

    if (socketIn 9= null)  socketIn.c#ose();  } catch (IO!ception e!) {}  try {

    if (service 9= null)

    Service and Process Programming ; etork communication and services : 

  • 8/16/2019 Network Communication and Services

    8/47

      service.c#ose();  } catch (IO!ception e!) {}  }

     Also" i! we have a %raphical application" and we use the sockets or streams !romdi!!erent events" we will not be able to use the try-it%-resource clause" and we willneed to use several try  clauses to use the socket" or the streams" or close them" in

    di!!erent parts o! our application. e will see this in e6ercise .!.1.'. Some useful met(ods

  • 8/16/2019 Network Communication and Services

    9/47

    uppercase. or instance" i! it receives the messa%e >1ello>" it will return >1'LL7> tothe client.

    • Create a pro;ect !or the client side called %c(o)Client. :e!ine a socket that will

    connect to the server 2use >localhost> as server name" i! ou are runnin% bothpro;ects in the same machine3. hen the connection is set" the client constantl askthe user to enter a messa%e" and then it will send it to the server" waitin% !or thecorrespondin% echo.

    • The communication process will !inish when the server receives the messa%e >be>.

    2.2. Using U!P sockets

    hen we use 9:/ connections" we do not need to establish a previous connectionbetween client and server. 'ver time that we need to send a messa%e between them" wewill need to speci! the address and port number o! the receiver" and it will %et the sender address and port !rom the messa%e as well. e will work with atagramSocket  andatagramPacket classes.

    The steps that we need to !ollow re%ardin% 9:/ connections are#

    ). Create a !atagramSocket speci!in% a local I/ address and port.

  • 8/16/2019 Network Communication and Services

    10/47

    socket.setSo0imeout(,---); // , secon%s>try{  >  socket.receive(packet3);} catch (Interrupte%IO!ception e) {

      >}

    4. hen we !inish the communication" we must close the socket established. e canalso put the socket in the try  clause so that it will auto close when the clause!inishes.

    !.!.1. %&ample

    e are %oin% to implement the same e6ample shown in subsection +.).)" but in this casewe will use 9:/ protocol.

    The client side would be like this#

    public class 'reetD7C#ient{  public static void main(String* args)

    {  try (DatagramSocket m"Socket = new DatagramSocket())  {  // Create t+e packet to be sent  String te!t = $2e##o$;  byte* message = te!t.get"tes();  Datagram7acket packetS = new Datagram7acket(message& message.#engt+&  Inet8%%ress.get:oca#2ost()& ,---);  m"Socket.sen%(packetS); 

    // 3eceive t+e response  byte* bu66er = new byte

  • 8/16/2019 Network Communication and Services

    11/47

     // 'et +ost an% port 6rom t+e message

      int %est7ort = packet3.get7ort();  Inet8%%ress %est8%%r = packet3.get8%%ress();

      // Create t+e response to be sent  String te!t = $'oo%b"e$;

      byte* message = te!t.get"tes();  Datagram7acket packetS = new Datagram7acket(message& message.#engt+&  %est8%%r& %est7ort);  m"Socket.sen%(packetS); 

    } catch (IO!ception e) {  S"stem.out.print#n(e);  }  }}

    !.!.!. Some implementation issues

     As ou can see" a data%ram is composed o!#• The in!ormation or messa%e to be sent

    • The messa%e len%th

    • :estination I/ and port number 

    • Local I/ and port number 2added automaticall when creatin% the data%ram3

    Note that" when we create a data%ram packet to be sent" we convert the messa%e 2Strin%3into a bte arra" with the getytesNo translation !ound>.

    •  A pro;ect called UPictionar*)Server  that will run on port @000. It will have a

    collection 2hash table or somethin% similar3 with some words in 'n%lish 2kes3 andtheir correspondin% Spanish translation 2values3. The server will read the word sentb the client" and it will return the Spanish translation o! that word. I! the word can=tbe !ound in the collection" the server will not return anthin%.

    Service and Process Programming ; etork communication and services 11

  • 8/16/2019 Network Communication and Services

    12/47

    2.3. #ore a$out t%e Inet&ddress class

    ou should have read about the Inet&ddress class be!ore in this unit" althou%h we havenot e6plained it in detail. It representes an I/ address in ,ava" but it also has methods thatconnect to a :NS server and resolve a hostname. In other words" we can use an ob;ect o! this class to connect to a remote server" either b its I/ address 2not ver usual3 or b its

    domain name" that is automaticall converted into an I/ address.

    To create an Inet&ddress ob;ect" we must use one o! its static !actor methods. The mostcommon is

    Inet8%%ress a%%ress = Inet8%%ress.get"Name($.m"server.com$);

    This method makes a connection to the local :NS server to look up the name and itscorrespondin% I/ address. e can also use this method to do a reverse lookup" this is" %etthe hostname !rom the I/ address#

    Inet8%%ress a%%ress = Inet8%%ress.get"Name($,-

  • 8/16/2019 Network Communication and Services

    13/47

      {  DataInputStream socketIn = null;  DataOutputStream socketOut = null;  try

    {socketIn = new DataInputStream(service.getInputStream());

      socketOut = new DataOutputStream(service.getOutputStream());

      // > Communication it+ c#ient 

    } catch (IO!ception e) {  S"stem.out.print#n(e);  } finally {  try {  if (socketOut 9= null)  socketOut.c#ose();  } catch (IO!ception e!) {}  try {

    if (socketIn 9= null)  socketIn.c#ose();

      } catch (IO!ception e!) {}  try {

    if (service 9= null)  service.c#ose();  } catch (IO!ception e!) {}  }  }}

    Note that" in this case" we can=t use the try clause to de!ine the socket and input streamsinside 2i.e. use the try-it%-resource clause3" because the Socket  ob;ect is created in theserver main ob;ect" and passed to the thread" so it would be closed b the server be!orethe thread could use it. So" we can use a inally  clause to close the socket and the inputand output streams !rom the thread.

    I! we work with 9:/ servers" we do not need to use an thread" since ever data%ramsent or received has no relationship with the others" and we do not need to establish adi!!erent connection with each client. e onl need to de!ine a loop where the server receives data%rams" %ets the remote I/ and port number" and sends a response to it.

    while (true){  byte* sent = new byte

  • 8/16/2019 Network Communication and Services

    14/47

    6@ercise 3

    Improve e6ercise ) with these two chan%es#

    • ake the client-server connection independent !rom the machines where the are

    placed. This is" ou must not use >localhost> as the server address. Instead o! this"let the user speci! the server address.

    •  Allow more than one client connectin% to the server. Then" the server will have to

    echo the messa%es !rom di!!erent clients" sendin% each one its answers.

    • Call the new pro;ects %c(oImproved)Server  and %c(oImproved)Client.

    Service and Process Programming ; etork communication and services 14

  • 8/16/2019 Network Communication and Services

    15/47

    '. Some special connections

    In this section we are %oin% to deal with some special tpes o! connections" such asmulticast connections and ob;ect serialiBation.

    3.1. #ulticast sockets

    e use multicast sockets when we want to send the same in!ormation to a %roup o! clientsat the same time. &e!ore doin% this" we need to create a multicast group" b assi%nin% allthe components o! the %roup the same I/ address 2o! class :3" and the same 9:/ portnumber.

  • 8/16/2019 Network Communication and Services

    16/47

    6@ercise  

    Create a multicast application that implements a chat.

    • The client side will be a ,avaD application in a pro;ect called

    +ulticastC(at)Client with the !ollowin% appearance#

     At the be%innin%" it will ask the user to introduce his nickname at the top o! thewindow" and then it will tr to connect to server. 7nce it connects to the server" theuser will be able to send messa%es with the lower te6t !ield. It will receive the

    messa%es sent b everone and will print them in the main te6t area. As soon asthe window client is closed" the connection must be closed as well.

    To receive messa%es !rom the %roup periodicall" ou will need to implement an o! the thread-sa!e methods o! communicatin% with a ,avaD application seen in 9nit *2section 3. or instance" ou can implement a Service  that periodicall receivesmessa%es !rom the %roup and prints them in the te6t area.

    • In this case" we will not need an server side" since ever client will send messa%es

    to the %roup and receive messa%es !rom it.

    3.2. '$(ect seriali)ation

    hen we talk about serialiBin% an ob;ect" we actuall talk about convertin% it into a bitse5uence" so that it can be sent throu%h a connection or stream. In ,ava" we can serialiBean simple value 2int" char" double...3 or an ob;ect that implements the Seriali)a$leinter!ace. I! it is a compound ob;ect" all o! its attributes must be simple" or implement thisinter!ace.

    To send or receive ob;ects !rom a stream" we use '$(ectInputStream  and'$(ect'utputStream  classes. e can create them !rom basic InputStream  or 'utputStream ob;ets or methods" and when we have them" we can use their methodsread'$(ect  and rite'$(ect  to read or write serialiBable ob;ects !rom$to a %iven stream.

    Service and Process Programming ; etork communication and services 1* 

  • 8/16/2019 Network Communication and Services

    17/47

    '.!.1. S(aring classes and ob$ects between server and client

    The classes that we serialiBe and send between server and client must be shared betweenboth pro;ects. To do this" one option is to create a separate pro;ect with all the classesinvolved in the serialiBation process. This pro;ect should not be a ,ava application" but aclass librar" as there will not be an main class#

    Then" we add this pro;ect as a librar o! both pro;ects 2client and server3" !rom the

    Properties  panel o! each pro;ect# we ri%ht-click on the pro;ect name" select Propertiesoption and then click on 8i$raries option on the le!t list. inall" we click on the  &dd Pro(ect... button and select the pro;ect where the serialiBable classes are placed.

    '.!.!. Seriali,ation t(roug( TCP sockets

    ?iven a TC/ socket" we can create" !or instance" an '$(ect'utputStream !rom it and sendan ob;ect throu%h it#

    ObectOutputStream obOut = new ObectOutputStream(socket.getOutputStream());obOut.riteObect(m"Obect);

    In the same wa" we can create an '$(ectInputStream in a socket" and read ob;ects !rom

    it#ObectInputStream obIn = new ObectInputStream(socket.getInputStream());B"Obect ob = obIn.rea%Obect();

    6@ercise * 

    Create a serialiBation application with the !ollowin% pro;ects#

    • e are %oin% to work with user data. So" create a new pro;ect 2class librar3. Call it

    Userata)+odel" and de!ine a User  class inside" with the !ollowin% attributes# theuser lo%in and password 2Strin%s3" and the re%istration date" and the appropriateconstructors" %etters and setters. The constructor must leave the lo%in and

    Service and Process Programming ; etork communication and services 1: 

  • 8/16/2019 Network Communication and Services

    18/47

    password empt 2>>3" and the re%istration date will be automaticall !illed withcurrent date.

    •  A server pro;ect called Userata)Server . hen a client connects" the server will

    create a new 9ser 2!rom User class e6plained be!ore3. Then" it will send that User ob;ect to the client" and wait !or a response.

    •The client pro;ect will be called Userata)Client. It will connect to the server"receive the User  ob;ect" and then it will ask the user to !ill its lo%in and password.7nce this data is completed" the client will send the User  ob;ect back to the server.

    • hen the server receives the complete User  ob;ect" it will print its in!ormation in the

    console.

    '.!.'. Seriali,ation t(roug( UP sockets

    I! we are workin% with 9:/ sockets" then we need to convert our serialiBable ob;ects intobte arras" so that we can put them in the data%ram packets. e will useyte&rrayInputStream and yte&rray'utputStream ob;ects to read and write ob;ects in

    this case.So" to write a serialiBable ob;ect in a 9:/ socket" we !ollow these steps#

    // rite t+e obect in a "te8rra"OutputStream"te8rra"OutputStream bs = new "te8rra"OutputStream();ObectOutputStream obOut = new ObectOutputStream(bs);obOut.riteObect(m"Obect);// 'et t+e b"te arra" 6rom t+e ritten obectbyte* b"tes = bs.to"te8rra"();// No& e ust sen% t+e b"te arra" as e %i% be6ore it+ D7 sockets

    I! we want to read a serialiBable ob;ect !rom a 9:/ socket" then we do this#

    // 3eceive t+e b"te arra"& as e %i% be6ore it+ D7 socketsbyte* b"tes = new byte

  • 8/16/2019 Network Communication and Services

    19/47

    buer=s name" and will send the updated product to the clients" to make them know whowon the auction.

    1ere ou can see an e6ample o! how it should work...

    ). Initiall" the server creates a product" with a name and initial price. or instance">Dbo6 7ne>" )00 euros.

    +. Then" it will wait !or * clients to connect

    *. Ne6t" it will send the whole Product  ob;ect to each client. So the will see thisin!ormation on their consoles#

    Product name: Xbox One

    Product initial price: 100 euros

    4. Then" each client will be asked to introduce his name and o!!er" in the same !ormate6plained be!ore. or instance" we mi%ht have these three o!!ers !rom the * di!!erentclients#

    nacho 150

    arturo 170

    ana 120

    . The server will receive these * messa%es" compare them and pick up the one withthe hi%hest o!!er. Then" it will update the product data with the buer=s name andprice" and send the in!ormation back to the clients. So" the clients would see thisin!ormation as the !inal result#

    Final price: 170 euros

    Buyer's name: arturo

    Call the pro;ects -uction)+odel  2class librar to store the Product class3"-uction)Server and -uction)Client. ou can also add an additional class or methodthat ou ma need 2!or instance" to mana%e clients connected to server3

    Service and Process Programming ; etork communication and services 1"

  • 8/16/2019 Network Communication and Services

    20/47

    4. T/ and ST/ client

    In this section we=ll see how ,ava can connect to T/ and ST/ 2email3 as a client.

    4.1 +TP Client To access a T/ server throu%h ,ava we=ll use Apache=s TPClientclass which is included in Apache=s Commons Net librar.

    4.1.1 Connection

    The most simple wa to connect to an e6istin% T/ server throu%h T/ protocol 2ou canconnect to an T/ server throu%h 1TT/ protocol also3 is openin% a connection like this#

    107C#ient 6tp = new 107C#ient();try {

    6tp.setContro#nco%ing($01EF$); // Important (be6ore connect)

    6tp.connect($

  • 8/16/2019 Network Communication and Services

    21/47

    4.1.' Uploading files

    &e!ore uploadin% a !ile to the server we must know i! that !ile is in binar or te6t !ormat andset the T/ de!ault !ile tpe to be trans!erred previous to send it. This is accomplished withsetileT*peint t*pe2  method. (alid values are TP.-SCII)I3%)TP%  2de!ault3 or TP."IN-/)I3%)TP% 2recommended i! ou don=t know the tpe o! a !ile3.

    7ther use!ul methods are c(ange5orkingirector*String pat(name2 that chan%es thecurrent workin% director in the T/ server and c(angeToParentirector*2   whichchan%es to the parent director.

    public static void up#oa%1i#e(boolean is0e!t& String 6i#e7at+&String nameInServer) {

    if(9connect()) { // 0+is is a met+o% e +ave create% to open a connectionS"stem.err.print#n($Cannot up#oa% 6i#e& error connecting9$);return;

    }

    try(1i#eInputStream in = new 1i#eInputStream(6i#e7at+)) {

    ftp.set1i#e0"pe(is0e!tH107. ASCII_FILE_TYPE 4107. BINARY_FILE_TYPE );  if(9ftp.store1i#e(nameInServer& in)) {  S"stem.err.print#n($rror up#oa%ing 6i#e $ 5 6i#e7at+ 5

    $ ($ 5 ftp.get3ep#"String() 5 $)$);  } else {  S"stem.out.print#n($1i#e $ 5 6i#e7at+ 5

    $ up#oa%e% it+ name $ 5 nameInServer);  }  } catch (IO!ception e) {  S"stem.err.print#n($rror up#oa%ing 6i#e $ 5 6i#e7at+ 

    5 e.getBessage());  }

    }

    4.1.4 ownloading files

    To download a !ile is a ver similar process but usin% a ile7utputStream on the local!ilename and the method retrieveile.

    public static void %on#oa%1i#e(boolean is0e!t& String nameInServer& String name:oca#) {if(9connect()) {

    S"stem.err.print#n($Cannot %on#oa% 6i#e& error connecting9$);return;

    }

    try(1i#eOutputStream out = new 1i#eOutputStream(name:oca#)) {ftp.set1i#e0"pe(is0e!tH107. ASCII_FILE_TYPE 4107. BINARY_FILE_TYPE );

      if(9ftp.retrieve1i#e(nameInServer& out)) {  S"stem.err.print#n($rror %on#oa%ing 6i#e $ 5 nameInServer 5  $ ($ 5 ftp.get3ep#"String() 5 $)$);  } else {  S"stem.out.print#n($1i#e $ 5 nameInServer 5

    $ %on#oa%e% it+ name $ 5 name:oca#);  }} catch (IO!ception e) {  S"stem.err.print#n($rror %on#oa%ing 6i#e $ 5 nameInServer 5

      e.getBessage());}

    }

    Service and Process Programming ; etork communication and services 21

    https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#setFileType(int)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#changeWorkingDirectory(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#changeToParentDirectory()https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#retrieveFile(java.lang.String,%20java.io.OutputStream)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#retrieveFile(java.lang.String,%20java.io.OutputStream)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#setFileType(int)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#changeWorkingDirectory(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#changeToParentDirectory()https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#retrieveFile(java.lang.String,%20java.io.OutputStream)

  • 8/16/2019 Network Communication and Services

    22/47

    4.1.6 0t(er operations

    •   rename(String from, String to) E Chan%es a remote !ile=s name.

    •   deleteFile(String pathname) E :eletes a remote !ile.

    •   removeDirectory(String pathname) E :eletes a director" onl i! it=s empt.

    •   makeDirectory(String pathname) E Creates a new subdirector.

    •   printWorkingDirectory() E ?ets the name o! the current workin% director.

    •   listNames() E ?ets 2onl the names3 the list o! !iles inside the current director.

    6@ercise 0 

    Create a ,avaD 2b code or DL3 application called TP+anager . It will be a simpleT/ client" which ou=ll use to connect to a server 2can be localhost or a virtual machineI/3" list its contents on a List(iew and do several actions. The application aspect should be

    more or less like this#

     

     As ou can see" once ou enter a server address" a lo%in name and password" and clickthe Connect button" the application will list the workin% director contents. The otherbuttons will per!orm the !ollowin% actions#

    • Upload# ill open a ileChooser dialo% to select a !ile that will be uploaded to theT/ server 2current director3.

    • owload7%nter # 7nl active when somethin% in the list is selected. Two situations

    can happen.

    ◦ I! the selected item is a director" the application will chan%e to that director

    listin% its !iles.

    ◦ I! it=s a normal !ile" the application will open a :irectorChooser dialo% to select a

    local director and download the !ile there.

    • 8o up# ill chan%e to the parent director and list its contents.

    Service and Process Programming ; etork communication and services 22 

    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html?is-external=truehttps://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#deleteFile(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#removeDirectory(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#makeDirectory(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#printWorkingDirectory()https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#listNames()http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html?is-external=truehttps://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#deleteFile(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#removeDirectory(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#makeDirectory(java.lang.String)https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#printWorkingDirectory()https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#listNames()

  • 8/16/2019 Network Communication and Services

    23/47

    • elete# 7nl active when somethin% in the list is selected. ill delete the !ile.

    There will be a label where ou=ll show ever action=s result" whether it=s a success or an!ailure. hen it=s needed" re!resh the list=s contents.

    4.2 S#TP Client ST/ is a protocol used !or email transmissions between servers. The de!ault ports usedin this protocol are + and 8F 2this one !or submittin% a new email3. or receivin% emails"IA/ and /7/* protocols are used.

    4.!.1 Initial steps

    To simpli! thin%s" we=re %oin% to use ?oo%le=s ?ail server to send emails !rom our ,avaapplication.

    irst" it should be pointed out that since +0)" ?oo%le doesn=t allow simple authentication2username and password3 b de!ault to lo% in its accounts. :evelopers must use 7Auth+and in this link ou=ll see an e6ample o! how to use it.

    1owever" we can still use the old and more simple method 2but less secure3 to connect to?ail server 2and compatible with other ST/ servers3. To enable it" ou must connect tothe ?ail account ou wish to use !or sendin% emails 2ou can create a new account3" and!ollow this link#

    https#$$www.%oo%le.com$settin%s$securit$lesssecureapps

    Then" ou=ll have to activate the option to allow the less secure access !or applications.

    Now" we=ll need to download ;a6a.mail and activation ,A< libraries to include in our pro;ectlibrar path.

    ,ava6.mail ,A< download.

    ,ava Activation ramework download.

    4.!.! Sending an email

    To send an email we=ll make use o! Properties class to de!ine the con!i%uration !or theST/ connection. Then" we=ll open a connection with the server and send a simple emailwith sub;ect" bod" and * destination addresses 2one directl and the other + with cop3.

    public class Bain {

    final static String senderEmail = $ ,%am.iessanvicenteAgmai#.com$;  final static String senderPassword  = $iessanvicente$;  final static String emailSMTPserver = $smtp.gmai#.com$;  final static String emailServerPort = $@FG$;

    public static void main(String* args) {7roperties props = new 7roperties();

    Service and Process Programming ; etork communication and services 23

    https://developers.google.com/gmail/api/quickstart/javahttps://www.google.com/settings/security/lesssecureappshttps://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/http://mvnrepository.com/artifact/javax.activation/activationhttps://docs.oracle.com/javase/8/docs/api/java/util/Properties.htmlhttps://developers.google.com/gmail/api/quickstart/javahttps://www.google.com/settings/security/lesssecureappshttps://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/http://mvnrepository.com/artifact/javax.activation/activationhttps://docs.oracle.com/javase/8/docs/api/java/util/Properties.html

  • 8/16/2019 Network Communication and Services

    24/47

      props.put($mai#.smtp.user$& senderEmail);  props.put($mai#.smtp.+ost$& emailSMTPserver);  props.put($mai#.smtp.port$& emailServerPort);  props.put($mai#.smtp.startt#s.enab#e$& $true$);  props.put($mai#.smtp.aut+$& $true$);  props.put($mai#.smtp.socket1actor".port$& emailServerPort);  props.put($mai#.smtp.socket1actor".c#ass$&

     $ava!.net.ss#.SS:Socket1actor"$);props.put($mai#.smtp.connectiontimeout$& $@---$); // 0imeout 

    try {  8ut+enticator aut+ = new 8ut+enticator() {  public 7assor%8ut+entication get7assor%8ut+entication() {  return new 7assor%8ut+entication(

    senderEmail& senderPassword );  }

    };//Open connection

      Session session = Session.getInstance(props& aut+);

      Bessage msg = new BimeBessage(session);  msg.set0e!t($Samp#e message$);  msg.setSubect($Samp#e subect$);  msg.set1rom(new Internet8%%ress(senderEmail));  msg.a%%3ecipient(Bessage.3ecipient0"pe.TO&  new Internet8%%ress($arturoAiessanvicente.com$));  msg.a%%3ecipients(Bessage.3ecipient0"pe.CC& new 8%%ress* {  new Internet8%%ress($noe!isteAiessanvicente.com$)&  new Internet8%%ress($noe!iste,Aiessanvicente.com$)  });  0ransport.send (msg);  S"stem.out.print#n($sent success6u##"$);  } catch (!ception e!) {

      S"stem.err.print#n($rror occurre% +i#e sen%ing.9$);  }

    }}

    6@ercise "

    Create a ,avaD application called+ailSender9 that will send an email.

    This application will connect to a ?mailaccount and send an email to an other account" The account can be one that ouhave created or the !ollowin%#+dam.iessanvicenteG%mail.comPass# iessanvicente

    The application will in!orm the user i! everthin% went well or there was anerror.

    Service and Process Programming ; etork communication and services 24

    mailto:[email protected]:[email protected]

  • 8/16/2019 Network Communication and Services

    25/47

    . 1TT/2S3 and eb Services

    Nowadas" most applications rel on web services to access remote and centraliBed datastored in a remote server throu%h the orld ide eb. A web service is a technolo%

    which uses a series o! standards in order to communicate an application runnin% in theserver 2usin% an technolo% like /1/"

  • 8/16/2019 Network Communication and Services

    26/47

    public static void main(String* args) {u66ere%3ea%er bu6Input = null;try {

    3: goog#e = new 3:($+ttp4//.goog#e.es$);3:Connection conn = goog#e.openConnection();

    String c+arset = getCharset(conn.get2ea%er1ie#%($ContentE0"pe$));

    bu6Input = new u66ere%3ea%er(new InputStream3ea%er(conn.getInputStream()& c+arset));

    String #ine;while((#ine = bu6Input.rea%:ine()) 9= null) {

    S"stem.out.print#n(#ine);}

    } catch (Ba#6orme%3:!ception e) {...} catch (IO!ception e) { ...} finally {

    if(bu6Input 9= null) {

    try {bu6Input.c#ose();

    } catch (IO!ception e) {...}}

    }}

    6.1.! :ttpU/3Connection and following redirections

    The class 1ttp9

  • 8/16/2019 Network Communication and Services

    27/47

    6.1.' Using an e&ternal 3ibrar* -s*nc:ttpClient2

    There are libraries like  Asnc1ttpClient  that simpli!ies a lot1TT/ connections. I! the pro;ect is not usin% tools like avenor ?radle" ou=ll have to download and add the necessarlibraries 2,A

  • 8/16/2019 Network Communication and Services

    28/47

    .2 asic /e$ Service access

    To access a

  • 8/16/2019 Network Communication and Services

    29/47

    in!ormation we can use the or%.;son A/I  2also present in  Android3 or other options like?oo%le=s ?S7N" but there are a lot o! options.

    Let=s see an e6ample. Ima%ine that we receive this in!ormation !rom a web web service in,S7N !ormat#

    {$error$46a#se&$person$4 {

    $name$4$7eter$&$age$4J-&$a%%ress$4

    {$cit"$4$:on%on$&$street$4$Some street ,$}&{$cit"$4$Ne Pork$&$street$4$Ot+er street

  • 8/16/2019 Network Communication and Services

    30/47

    }

    AOverri%epublic String toString() {

    String str = $Name E $ 5 name 5 $Rnage E $ 5 age 5$Rn8%%ress E$;

    for(8%%ress a4 a%%ress)

    str 5= $RnRt$ 5 a.toString();

    return str;}

    }

    inall" we need to connect to the web service" %et its response and process the strin%containin% the resultin% ,S7N code 28etService/esponse is a custom class !or connectto a web service and return its response3#

    public static void main(String* args) {'etService3esponse resp = new 

    'etService3esponse($+ttp4//#oca#+ost/services/e!amp#e

  • 8/16/2019 Network Communication and Services

    31/47

    }

    I! the !ield names are correctl names " it will map everthin% automaticall#

    public static void main(String* args) {'etService3esponse resp =

    new 'etService3esponse($+ttp4//#oca#+ost/services/e!amp#e

  • 8/16/2019 Network Communication and Services

    32/47

    new 3:($+ttp4//#oca#+ost/services/sumEservice.p+pHnum

  • 8/16/2019 Network Communication and Services

    33/47

    resu#t:abe#.setisib#e(false);

    gss.setOnSuccee%e%(e E {resu#t:abe#.set0e!t($3esu#t4 $ 5 gss.geta#ue());a%%utton.setDisab#e(false);img:oa%.setisib#e(false);resu#t:abe#.setisib#e(true);

    });}

    AOverri%epublic void initia#iUe(3: ur#& 3esourceun%#e rb) {}

    }

    0+is is +o it i## #ook #ike +en processing t+e reTuest (t+e +ee# is a%on#oa%e% animate% gi6)4

    . 56T7 P'ST7 PUT7 !686T6 

    The 4 common operations in

  • 8/16/2019 Network Communication and Services

    34/47

    4 methods !or operations" !or e6ample" with $productJ resource to operate with productsstored in the database" some !rameworks like An%ular,S in ,avascript o!!er a reallsimpli!ied wa to make these operations.

    Let=s see how to interact with web services that support these operations in ,ava#

    6.6.1 Upgrading AProduct +anagerB to use web services

    To help with the e6planation we=ll modi! the application /roduct ana%erJ used in unit +"so that products are stored in a server with a database and operations with those productswill be done throu%h web services in /1/ 29sin% /halcon in icro!ramework mode3.

    In the server 2which is the same computer where the applicationruns in our e6ample3 there is a database with a table !or products and a table !or cate%ories#

     And the structure o! both tables 2cate%or and product3#

     

    To interact with the database and create web services" we=ll use the P(alcon !ramework in/1/" which is a complete and power!ul !ramework" and the !astest in /1/ because it=scompiled !rom C lan%ua%e and loaded as a librar 2binar3. 7ther !rameworks are written

    in /1/ directl" which is much slower than compiled code. ou should be able to downloadeverthin% 2;ava" php and s5l3 !rom Aula (irtualJ to tr this application.

    6.6.! 8eneric web service access

    To avoid repeatin% code as much as possible" we have created a class with a staticmethod !or accessin% a web service and %ettin% a response. This method" calledget/esponse" receives * parameters# the url to connect" the data to send in the bod o! the re5uest 2or null i! there=s no data3" and the operation or method 2?'T" /7ST" /9T":'L'T'3.

     Also" some 1TT/ headers have been established so that the re5uest is similar to what a

    web browser would send" like the ori%in domain 2in this case localhost3" the pre!erredlan%ua%e 2Spanish3" the possibilit to compress data 2%Bip3 in order to save bandwidth" atime out !or the connection" or the data tpe used !or communication 2application$;son3.

    public class Serviceti#s {

      // 'et c+arset enco%ing (01EF& ISO&...)  public static String getC+arset(String content0"pe) {  for (String param 4 content0"pe.rep#ace($ $& $$).sp#it($;$)) {  if (param.startsit+($c+arset=$)) {  return param.sp#it($=$& ,)

  • 8/16/2019 Network Communication and Services

    35/47

      return null; // 7robab#" binar" content  }

      public static String get3esponse(String ur#& String %ata& String met+o%) {  u66ere%3ea%er bu6Input = null;  StringQoiner resu#t = new StringQoiner($Rn$);  try {

      3: ur#Conn = new 3:(ur#);  2ttp3:Connection conn =(2ttp3:Connection) ur#Conn.openConnection();

      conn.set3ea%0imeout(,---- /Wmi##isecon%sW/);  conn.setConnect0imeout(

  • 8/16/2019 Network Communication and Services

    36/47

      } catch (IO!ception e) { }  }  }

      return resu#t.toString();  }}

    6.6.' 8%T

    8%T operations are intended to retrieve e6istin% ob;ects !rom the database 2S'L'CT3. Inthis case" there are + web services#

    •  A service usin% the resource $cate%orJ that %ets all cate%ories in the database#

    •  A service usin% the resource $productJ that receives a cate%or id and returns allproducts that are part o! that cate%or 2Notice that when we receive a List o! ob;ects" we need com.google.gson.reflect.T*peToken  and $ava.lang.reflect.T*peclasses i! we intend to use ?S7N librar3#

    This is the ,avaD Service that will %et the cate%ories#

     And this is the service that will %et the products !rom a cate%or#

    Service and Process Programming ; etork communication and services 3* 

  • 8/16/2019 Network Communication and Services

    37/47

    To end this ?'T e6ample" we=ll see how we re5uest products when a new cate%or isselected in the application#

    6@ercise 11

    Create a pro;ect named 8etCompanies in ,avaD. It will use these two web servicesusin% ?'T#

    • (ttp>77IP addressD7e&ercises7compan* E ill return all the companies with this

    ,S7N !ormat#

      O  >id># >)>"  >ci!># >C+*)4+*4>"  >name># >CraB Stu!! Inc.>"  >address># >adness Street )>  P"  O  >id># >+>"

    Service and Process Programming ; etork communication and services 3: 

  • 8/16/2019 Network Communication and Services

    38/47

      >ci!># >T)*4+*@>"  >name># >Sill Q :umb LT:>"  >address># >Idont Rnow Street" )*+4>  P"  ...

    • (ttp>77IP addressD7e&ercises7compan*7EidCompan*F G ill return the

    in!ormation o! a compan in this !ormat 2i! there=s in!ormation ou won=t need" likeidCompanJ" ;ust i%nore it and don=t include it in ,ava=s class3#

    O  >ok># true"  >error># >>"  >compan># O  >id># >*>"  >ci!># >(*+4)@'>"  >name># >aniacs International>"  >address># >1app Stress Street" >"  >emploees>#   O

      >id># >>"  >ni!># >4@*F48@9>"  >name># >Cocaine "  >a%e># >*F>"  >idCompan># >*>  P"  O  >id># >@>"  >ni!># >)+4+*@4R>"  >name># >1appsad indows>"  >a%e># >4F>"  >idCompan># >*>  P    PP

    irst" it will load all companies on the top list !rom the ade5uate web service. Then" when auser selects a compan" it will retrieve its in!ormation and emploees !rom the other webservice" showin% them in the bottom list. This application will look more or less like this#

    Service and Process Programming ; etork communication and services 30 

  • 8/16/2019 Network Communication and Services

    39/47

    6.6.4 P0ST

    9sin% /7ST" data is sent in the bod o! the re5uest. This is done b usin% the outputstream o! the connection to send that data. The !ormat can be 9

  • 8/16/2019 Network Communication and Services

    40/47

    6@ercise 12 

    9pdate the pro;ect 8etCompanies !rom e6ercise )) and insert an AddJ button !or addin%emploees. This button 2onl active when a compan is selected3 will open a new window

    containin% a !orm to add a new emploee.

    To create new window usin% another DL 2or buildin% the scene b code3" ou can do itlike this#

      Stage stage = ne Stage();

      stage.initBo%a#it"(Bo%a#it".877:IC80IONBOD8:); 

    7arent root = 1VB::oa%er.#oa%(getC#ass().get3esource($8%%mp#o"ee.6!m#$)); 

    Scene scene = ne Scene(root); 

    stage.set0it#e($8%% emp#o"ee$);  stage.setScene(scene);  stage.s+o();  stage.setOn2i%%en((e) E {  // p%ate t+e emp#o"ees #ist some+o...  });

    Service and Process Programming ; etork communication and services 4, 

  • 8/16/2019 Network Communication and Services

    41/47

  • 8/16/2019 Network Communication and Services

    42/47

     And !inall" this is how we create and start the Service !rom the controller#

    6.6.H %3%T%

    The :'L'T' operation works like ?'T 2variables in 9

  • 8/16/2019 Network Communication and Services

    43/47

    This is the ,avaD Service that will connect to this web service#

     And !inall" how we create and start the service !rom the controller#

    6@ercise 13

    9pdate the 8etCompanies pro;ect !rom e6ercises )) and )+. ou=ll have to add two morebuttons#

    • Update# 7nl active when an emploee is selected. It will open a window with a

    !orm 2similar to Add3 to edit an emploee=s in!ormation. It will connect to whi webservice and send in!ormation b /9T method#

    ◦ (ttp>77IP addressD7e&ercises7emplo*ee7Eid%mplo*eeF

    ◦ The in!ormation sent in ,S7N will have the same !ormat that when ou add an

    emploee 2see e6ercise *3" and the response will be a ,S7N ob;ect with two!ields E okJ 2boolean3 and errorJ 2Strin%3.

    • elete# ill open a dialo% to ask the user i! he$she wants to delete the selected

    emploee 2see /roductana%er e6ample application !rom unit +" or the updatede6ample in this unit3. I! positive answer is %iven it will call this web service 2usin%:'L'T' method3#

    Service and Process Programming ; etork communication and services 43

  • 8/16/2019 Network Communication and Services

    44/47

    ◦ (ttp>77IP addressD7e&ercises7emplo*ee7Eid%mplo*eeF

    ◦ The response will be a ,S7N ob;ect with the same !ormat as be!ore 2update3.

    .* 6mulating an &&9 call 

    Some !rameworks which run on the server side" di!!erentiate a normal 1TT/ re5uest !roman A,AD one 2done with ,avascript3. This is because when it=s a normal re5uest meansthat a browser is the client doin% that petition and a !ull 1TL document 2view3 must beserved. hen it=s an A,AD call" it usuall means that onl a !ra%ment o! 1TL or ,S7N isserved" and not a !ull 1TL document.

    or e6ample" with the /halcon !ramework" is use!ul to know when it=s a normal or an A,ADre5uest in order to load the !ull !ramework 2more power!ul but heavier3 or a micro!ramework 2less !unctionalit but more than enou%h !or web services3.

    This is how /halcon can detect an A,AD call#

    The server knowswhen it=s an A,AD call 2!rom ,avascript3 checkin% the 9/eJuested5it( header that mustcontain the value 9+3:ttp/eJuest. All we need to do to emulate these calls and makethe server believe that we are re5uestin% it !rom ,avaScript and %ettin% a ,S7N responseinstead o! a !ull 1TL document is addin% this header to the connection#

    .: #aintaining session it% cookies

    'ven i! we think that we don=t need to handle cookies in our application" there=s one casewhen it=s almost obli%ator 2unless we want to send lo%in in!ormation ever time we use a

    web service3" and it=s when there=s some tpe o! authentication at the be%innin%. The

    Service and Process Programming ; etork communication and services 44

  • 8/16/2019 Network Communication and Services

    45/47

    server will store in!ormation indicatin% that the lo%in was success!ul in a session and willanswer the client returnin% a cookie with the session id. That=s what the client has to sendto the server automaticall whenever it starts a connection" so the server can check i! alo%in has been previousl success!ul and which user is lo%%ed in 2amon% an other in!ormation that wants to store in the session3.

    Ima%ine that we have these + web services#

    The !irst one will store the name o! the user in a session variable called userJ" and willprint that name. hen we call the second service" it checks i! that session variable e6istsand prints its value or NoJ i! it doesn=t e6ist 2session usuall e6pires in a !ew minutes i! theclient doesn=t connect to the server meanwhile3. I! we don=t store the session id2automaticall %enerated b the server and sent with headers as a cookie3 in the client" wewon=t sent it in the second re5uest and the server will create a new session meanin% that itwill be empt and that variable won=t e6ist. This is the de!ault behaviour#

    7nl b addin% a line at the be%innin% o! the application in order to create acookie mana%er is enou%h !or ,ava to automaticall handle cookies like a web browser 2more or less3 and the session will work normall.

    Service and Process Programming ; etork communication and services 4 

    https://en.wikipedia.org/wiki/Session_IDhttps://en.wikipedia.org/wiki/Session_ID

  • 8/16/2019 Network Communication and Services

    46/47

    .8 Sendin% !iles

    or !iles" which some o! the are binar and contain non printable characters" sendin% their contents inside a ,S7N structure is not possible. 1owever" ou can convert a !ile into aprintable strin% usin% an encodin% mechanism" in this case we=ll use &ase@4.

    irst o! all" let=s take a look at the web service that will receive the !ile 2in this case it wille6pect to receive an ima%e" but we could check3 and store it in the server.

    ImportantK# The directories where we are %oin% to store !iles in the server must have writepermissions !or everbod as Apache uses its own user in the sstem.

     As ou can see" it will receive the !ile data encoded inside dataJ !ield" and at least the !ilename it had in the client inside the nameJ !ield. It will decode the !ile=s data and store it inthe server where the web service is located" inside public7img subdirector.

    e=re %oin% to use the class ServiceUtils that we created be!ore to make thin%s easier.

    irst" let=s take a look at the class used to represent a !ile ob;ect that will be serialiBed into,S7N b the ?son librar#

     As ou can notice. e store !ile=s data inside a Strin%" because that=s what the &ase@4

    encoder will %enerate when usin% its method encodeToString2" and it=s the most

    Service and Process Programming ; etork communication and services 4* 

  • 8/16/2019 Network Communication and Services

    47/47

    appropriate !ormat to include in the ,S7N bod. e also store !ile=s name and thedirector where it was located 2absolute path3.

    inall. Let=s take a look at an e6ample o! how to send the ima%e to the web service in themain method#

    Curiosities>

    I! ou don=t use a !ramework like /halcon. The recommended wa in /1/ to %et the ,S7Nsent 2instead o! a 9name># >I?U+0)*08*)U)F4@+4.;p%>"  >title># >Loval place>"  >desc># >place description>"  dataJ# base @4 encoded dataH.JP

     Access this address in our browser to checkall uploaded ima%es and delete them#