Sie sind auf Seite 1von 20

Unit-2 Networking Lecture-10: Introduction to networking:

Network is the interconnected collection of computers. In java networking is implemented by java.net.* package. All classes of networking must include the above package. Networking uses Socket and ServerSocket classes. Connecting to a server: Diagramatically it can be shown as below

Program for connecting to server :


/* This program describes receiving of messages from server computer */

SocketTest !ava import java.io.* import java.net.* import java.util.* public class Socket!est " public static void main#String$% args& " char ch

try " Socket s ' new Socket #(I) Address(* )ortno& InputStream inStream ' s.getInputStream#& Scanner in ' new Scanner#inStream& while #in.hasNe+t,ine#&& " String line ' in.ne+t,ine#& System.out.println#line& finally " s.close#& catch #I./+ception e& " e.printStack!race#& !he key statements of this simple program are as follows0 Socket s ' new Socket#(I) Address(* port no& InputStream inStream ' s.getInputStream#& !he first line opens a socket* which is an abstraction for the network software that enables communication out of and into this program. 1e pass the remote address and the port number to the socket constructor. If the connection fails* then an 2nknown3ost/+ception is thrown. If there is another problem* then an I./+ception occurs. 4ecause 2nknown3ost/+ception is a subclass of I./+ception and this is a sample program* we just catch

Lecture-11: Im"#ementing Server: A simple server that can send information to clients. .nce you start the server program* it waits for some client to attach to its port. 1e chose port number 5657* which is not used by any of the standard services. !he ServerSocket class establishes a socket. In our case* the command ServerSocket s ' new ServerSocket#5657& establishes a server that monitors port 5657. !he command Socket incoming ' s.accept#& tells the program to wait indefinitely until a client connects to that port. .nce someone connects to this port by sending the correct re8uest over the network* this method returns a Socket object that represents the connection that was made. 9ou can use this object to get input and output streams* as is shown in the following code0 InputStream inStream ' incoming.getInputStream#& .utputStream outStream ' incoming.get.utputStream#& /verything that the server sends to the server output stream becomes the input of the client program* and all the output from the client program ends up in the server input stream. In all the e+amples in this chapter* we will transmit te+t through sockets. 1e therefore turn the streams

into scanners and writers. Scanner in ' new Scanner#inStream& )rint1riter out ' new )rint1riter#outStream* true :* auto;lush *:& ,et<s send the client a greeting0 out.println#(3ello= /nter 49/ to e+it.(& 1hen you use telnet to connect to this server program at port 5657* you will see the preceding greeting on the terminal screen. In this simple server* we just read the client input* a line at a time* and echo it. !his demonstrates that the program receives the client<s input. An actual server would obviously compute and return an answer that depended on the input. String line ' in.ne+t,ine#& out.println#(/cho0 ( > line& if #line.trim#&.e8uals#(49/(&& done ' true In the end* we close the incoming socket. incoming.close#& !hat is all there is to it. /very server program* such as an 3!!) web server* continues performing this loop0 1 It receives a command from the client #(get me this information(& through an incoming data stream.
2. It somehow fetches the information. 3. It sends the information to the client through the outgoing data stream.

Program for Im"#ementing Server: :* !his program describe sending message to client $c%oServer !ava import java.io.* import java.net.* import java.util.* public class /choServer " public static void main#String$% args & " try " :: establish server socket ServerSocket s ' new ServerSocket#5657& :: wait for client connection Socket incoming ' s.accept# & try " InputStream inStream ' incoming.getInputStream#& .utputStream outStream ' incoming.get.utputStream#& Scanner in ' new Scanner#inStream& )rint1riter out ' new )rint1riter#outStream* true :* auto;lush *:& out.println# (3ello= /nter 49/ to e+it.( & :: echo client input boolean done ' false while #=done ?? in.hasNe+t,ine#&& " String line ' in.ne+t,ine#& out.println#(/cho0 ( > line& if #line.trim#&.e8uals#(49/(&& done ' true finally " incoming.close#& catch #I./+ception e& "

e.printStack!race#& !o try it out* compile and run the program. !hen* use telnet to connect to the following server and port0 Server0 6@A.B.B.6 )ort0 5657 !he I) address 6@A.B.B.6 is a special address* the local loopback address* that denotes the local machine. 4ecause you are running the echo server locally* that is where you want to connect. If you are connected directly to the Internet* then anyone in the world can access your echo server. Sending $-&ai#: !o send eCmail* you make a socket connection to port @D* the SE!) port. SE!) is the Simple Eail !ransport )rotocol that describes the format for eCmail messages. 9ou can connect to any server that runs an SE!) service. .n 2NIF machines* that service is typically implemented by the sendCmail daemon. 3owever* the server must be willing to accept your re8uest. It used to be that sendCmail servers were routinely willing to route eCmail from anyone* but in these days of spam floods* most servers now have builtC in checks and accept re8uests only from users* domains* or I) address ranges that they trust. .nce you are connected to the server* send a mail header #in the SE!) format* which is easy to generate&* followed by the mail message.

3ere are the details0 1 .pen a socket to your host. Socket s ' new Socket#(mail.yourserver.com(* @D& :: @D is SE!) )rint1riter out ' new )rint1riter#s.get.utputStream#&& 2 Send the following information to the print stream0 3/,. sending host EAI, ;G.E0 Hsender e-mail addressI GJ)! !.0 HIrecipient e-mail addressI DA!A mail message (any number of lines) .K2I! !he SE!) specification #G;J 5@6& states that lines must be terminated with Lr followed by Ln.Eost SE!) servers do not check the veracity of the informationyou may be able to supply any sender you like. #Meep this in mind the ne+t time you get an eCmail message from presidentNwhitehouse.gov inviting you to a blackCtie affair on the front lawn. Anyone could have connected to an SE!) server and created a fake message.& !he program in /+ample OCP is a simple eCmail program. As you can see in ;igure OCQ* you type in the sender* recipient* mail message* and SE!) server. !hen* click the Send button* and your message is sent.

Lecture-12: &aking U'L Connection: U'Ls and U'Is !he 2G, and 2G,Jonnection classes encapsulate much of the comple+ity of retrieving information from a remote site. 9ou can construct a 2G, object from a string0 2G, url ' new 2G,#urlString& If you simply want to fetch the contents of the resource* then you can use the openStream method of the 2G, class. !his method yields an InputStream object. 2se it in the usual way* for e+ample* to construct a Scanner0 InputStream inStream ' url.openStream#& Scanner in ' new Scanner#inStream& As of RDM 6.P* the java.net package makes a useful distinction between 2G,s #uniform resource locators& and 2GIs #uniform resource identifiers&. A 2GI is a purely syntactical construct that specifies the various parts of the string specifying a web resource. A 2G, is a special kind of 2GI* namely* one with sufficient information to locate a resource. .ther 2GIs* such as mailto0cayNhorstmann.com are not locatorsthere is no data to locate from this identifier. Such a 2GI is called a 2GN #uniform resource name&. In the Rava library* the 2GI class has no methods for accessing the resource that the identifier specifiesits sole purpose is parsing. In contrast* the 2G, class can open a stream to the resource. ;or that reason* the 2G,

class only works with schemes that the Rava library knows how to handle* such as http0* https0* ftp0 the local file system #file0&* and RAG files #jar0&. Using a U'LConnection to 'etrieve Information If you want additional information about a web resource* then you should use the 2G,Jonnection class* which gives you much more control than the basic 2G, class. 1hen working with a 2G,Jonnection object* you must carefully schedule your steps* as follows0 1 Jall the openJonnection method of the 2G, class to obtain the 2G,Jonnection object0 2G,Jonnection connection ' ur# o"enConnection() 2 Set any re8uest properties* using the methods setDoInput setDo.utput setIfEodifiedSince set2seJaches setAllow2serInteraction setGe8uest)roperty setJonnect!imeout setGead!imeout 1e discuss these methods later in this section and in the A)I notes. * Jonnect to the remote resource by calling the connect method. connection.connect#& 4esides making a socket connection to the server* this method also 8ueries the server for header information.

+ After connecting to the server* you can 8uery the header information. !wo methods* get3eader;ieldMey and get3eader;ield* enumerate all fields of the header. As of RDM 6.P* the method get3eader;ields gets a standard Eap object containing the header fields. ;or your convenience* the following methods 8uery standard fields. getJontent!ype getJontent,ength getJontent/ncoding getDate get/+piration get,astEodified , ;inally* you can access the resource data. 2se the getInputStream method to obtain an input stream for reading the information. #!his is the same input stream that the openStream method of the 2G, class returns.& !he other method* getJontent* isn<t very useful in practice. !he objects that are returned by standard content types such as te+t:plain and image:gif re8uire classes in the com. sun hierarchy for processing. Program for U'L Connection: import java.net.* import java.io.* import java.util.* class 2G,demo " public static void main#String args$ %& throws /+ception "

int i 2G, u ' new 2G,#http0::www.yahoo.com05B:inde+.html& System.out.println#Sprotocol nameT > u.get)rotocol# & & System.out.println#S3ost nameT > u.get3ost# & & System.out.println#Sport nameT > u.get)ort# & & System.out.println#Sfile nameT > u.get;ile# & & 2G,Jonnection uc'u.openJonnection# & System.out.println#Scontent typeT > uc.getJontent!ype# & & System.out.println#Scontent lengthT > uc.getJontent,ength# & & System.out.println#Slast modified dateT > new Date#uc.get,astEodified# & & System.out.println#S!he file contentsT & InputStream is'uc.getInputStream7 & while# I ' is.read# & = ' C6& System.out.println# #char& i & --dvance Socket Programming0 In the following sections* we cover advanced issues that arise in realCworld programs. 1e first show you how to use timeouts and interrupts to deal with connection errors. 1e show how the (halfCclose( mechanism can simplify re8uest protocol* and we finish with a section on Internet addresses.

Socket Timeouts In realClife programs* you don<t just want to read from a socket* because the read methods will block until data are available. If the host is unreachable* then your application waits for a long time and you are at the mercy of the underlying operating system to time out eventually. Instead* you should decide what timeout value is reasonable for your particular application. !hen* call the setSo!imeout method to set a timeout value #in milliseconds&. Socket s ' new Socket#. . .& s.setSo!imeout#6BBBB& :: time out after 6B seconds If the timeout value has been set for a socket* then all subse8uent read and write operations throw a Socket!imeout/+ception when the timeout has been reached before the operation has completed its work. 9ou can catch that e+ception and react to the timeout. try " Scanner in ' new Scanner#s.getInputStream#&& String line ' in.ne+t,ine#& ... catch #InterruptedI./+ception e+ception& " react to timeout

!here is one additional timeout issue that you need to address0 !he constructor Socket#String host* int port& can block indefinitely until an initial connection to the host is established. As of RDM 6.P* you can overcome this problem by first constructing an unconnected socket and then connecting it with a timeout0 Socket s ' new Socket#& s.connect#new InetSocketAddress#host* port&* timeout& Interru"ti.#e Sockets 1hen you connect to a socket* the current thread blocks until the connection has been established or a timeout has elapsed. Similarly* when you read or write data through a socket* the current thread blocks until the operation is successful or has timed out. In interactive applications* you would like to give users an option to simply cancel a socket connection that does not appear to produce results. 3owever* if a thread blocks on an unresponsive socket* you cannot unblock it by calling interrupt. !o interrupt a socket operation* you use a SocketJhannel* a feature of the java.nio package. .pen the SocketJhannel like this0 SocketJhannel channel ' SocketJhannel.open#new InetSocketAddress#host* port&& A channel does not have associated streams. Instead* it has read and write methods that make use of 4uffer objects. #See Uolume 6* Jhapter 6@ for more information about NI. buffers.& !hese methods are declared in interfaces Geadable4yteJhannel and 1ritable4yteJhannel. If you don<t want to deal with buffers* you can use the Scanner

class to read from a SocketJhannel because Scanner has a constructor with a Geadable4yteJhannel parameter0 Scanner in ' new Scanner#channel& !o turn a channel into an output stream* use the static Jhannels.new.utputStream method. .utputStream outStream ' Jhannels.new.utputStream#channel& !hat<s all you need to do. 1henever a thread is interrupted during an open* read* or write operation* the operation does not block but is terminated with an e+ception.

/ 1 0it% reference to socket e1"#ain c#ient server Communication in !ava 0rite a "rogram to "rint "rotoco#2 "ort2 %ost and fi#e of U'L S3LUTI3N: 1ith reference to socket client system receives information from server by Socket class of java.net.* package. ServerSocket class is used by server system to send data to client. Socket class takes two parameter one is I) address of server and other is port no of server. ServerSocket class uses only port no to send data to client system. C#ient server communication: Diagrammatically it can be shown as below

Program to "rint "rotoco#2"ort %ost and fi#e .4 U'L c#ass import java.net.* import java.io.* class 2G,demo " public static void main#String args$ %& throws /+ception "

int i 2G, u ' new 2G,#http0::www.yahoo.com05B:inde+.html& System.out.println#Sprotocol nameT > u.get)rotocol# & & System.out.println#S3ost nameT > u.get3ost# & & System.out.println#Sport nameT > u.get)ort# & & System.out.println#Sfile nameT > u.get;ile# & & / 2 5iscuss wit% e1am"#e %ow a c#ient a""#ication read a fi#e from server t%roug% U'LConnection S3LUTI3N: 2G,Jonnection and 2G, classes of java.net.* package is used by client to read file from server which is connected by internet connection. 2G, class object finds a reference of a file of server in the internet as below U'L u 6 new U'L(%tt":77www 4a%oo com:807inde1 %tm#)9 2G,Jonnection class object makes a connection wirh the file of server referenced by 2G, class object as below U'LConnection uc6u o"enConnection( )9 2G,Jonnection class object reads the data of file as follows In"utStream is6uc getIn"utStream( )9 w%i#e( I 6 is read( ) : 6 -1) S4stem out "rint#n( (c%ar) i )9

Program for U'L Connection to read a fi#e from server: import java.net.* import java.io.* import java.util.* class 2G,demo " public static void main#String args$ %& throws /+ception " int i 2G, u ' new 2G,#http0::www.yahoo.com05B:inde+.html& 2G,Jonnection uc'u.openJonnection# & System.out.println#Scontent typeT > uc.getJontent!ype# & & System.out.println#Scontent lengthT > uc.getJontent,ength# & & System.out.println#Slast modified dateT > new Date#uc.get,astEodified# & & System.out.println#S!he file contentsT & InputStream is'uc.getInputStream# & while# I ' is.read# & = ' C6& System.out.println# #char& i & / * 5escri.e %ow a server sends data to c#ient S3LUTI3N:

Server sends information to clients after starting the server program it waits for some client to attach to its port. 1e chose port number for e+ample 5657* which is not used by any of the standard services. !he ServerSocket class establishes a socket. the command is ServerSocket s 6 new ServerSocket(818;)9 /stablishes a server that monitors port 5657. !he command is Socket incoming 6 s acce"t()9 tells the program to wait indefinitely until a client connects to that port. .nce someone connects to this port by sending the correct re8uest over the network* this method returns a Socket object that represents the connection that was made. 9ou can use this object to get input and output streams* as is shown in the following code0 In"utStream inStream 6 incoming getIn"utStream()9 3ut"utStream outStream 6 incoming get3ut"utStream()9 /verything that the server sends to the server output stream becomes the input of the client program* and all the output from the client program ends up in the server input stream. 1e will transmit te+t through sockets. 1e therefore turn the streams into scanners and writers. Scanner in 6 new Scanner(inStream)9 Print0riter out 6 new Print0riter(outStream2 true 7< auto=#us% <7)9 ,et<s send the client a greeting0 out "rint#n(>?e##o: $nter @A$ to e1it >)9 In the end* we close the incoming socket. incoming c#ose()9

/very server program* such as an 3!!) web server* continues performing this loop0 1 It receives a command from the client #(get me this information(& through an incoming data stream.
2 It somehow fetches the information. * It sends the information to the client through the outgoing data stream.

Program for sending data from Server to C#ient: :* !his program describe sending message to client $c%oServer !ava import java.io.* import java.net.* import java.util.* public class /choServer " public static void main#String$% args & " try " :: establish server socket ServerSocket s ' new ServerSocket#5657& :: wait for client connection Socket incoming ' s.accept# & try " InputStream inStream ' incoming.getInputStream#& .utputStream outStream ' incoming.get.utputStream#& Scanner in ' new Scanner#inStream& )rint1riter out ' new )rint1riter#outStream* true :* auto;lush *:& out.println# (3ello= /nter 49/ to e+it.( & :: echo client input boolean done ' false while #=done ?? in.hasNe+t,ine#&& " String line ' in.ne+t,ine#& out.println#(/cho0 ( > line&

if #line.trim#&.e8uals#(49/(&& done ' true finally " incoming.close#& catch #I./+ception e& " e.printStack!race#& -

Das könnte Ihnen auch gefallen