Title: Java Training Sockets and Network Programming
1Java TrainingSockets and Network Programming
2What is a Socket?
- A communications channel between two computers
- A socket on one computer can talk talk to a
socket on another computer via this a
communication channel - It is a lower level communications mechanism than
technologies such as web services, CORBA, RMI, or
IIOP - Two main types of sockets supported in Java
- TCP sockets (implemented by the Socket class)
- UDP sockets (implemented by the DatagramSocket
class) - TCP sockets are generally more commonly used and
simpler. - These slides will describe TCP sockets.
3TCP/IP Sockets -1
- TCP/IP Transfer Control Protocol Internet
Protocol - TCP is a reliable point-to-point communication
protocol that client-server applications on the
Internet use to communicate with each other - To communicate over TCP, a client program and a
server program establish a connection to one
another - The client and server programs both bind a socket
to each end of the connection and communicate by
reading and writing to those sockets - There are three commonly used socket classes in
the java.net package
4TCP/IP Sockets -2
Client requests connection
Client
Server
Port
Port
Client
Server
Connection accepted
Port
Port
Upon acceptance, the server gets a new socket
bound to the same local port and also has its
remote endpoint set to the address and port of
the client. It needs a new socket so that it can
continue to listen to the original socket
for connection requests while tending to the
needs of the connected client.
5URLConnection -1
URLConnection - abstract superclass for
communications links between an application and a
URL. HttpURLConnection is a commonly used
subclass
6URLConnection -2
- Basic Steps in Using URLConnection to retrieve
web page - Create URL object with a valid URL string. If the
URL is invalid, youll get a MalformedURLException
- Open a connection on that URL (openConnection()
method) - Wrap the InputStream for that connection in a
BufferedReader so you can read lines - Read the web page using your BufferedReader
- Call your BufferedReaders close() method
7URLConnection -3
- URL url new URL(http//www.wrfportal.org/index.
html) - URLConnection urlCon url.openConnection()
//connect to this URL - //use the urlCons InputStream to create a
BufferedReader - InputStream inputStream urlCon.getInputStream()
- InputStreamReader isr new InputStreamReader(inpu
tStream) - BufferedReader bufReader new BufferedReader(isr)
- String line null
- while ((line bufReader.readLine()) ! null)
//read lines from URL until null - System.out.println(line "\n")
- bufReader.close() //close the BufferedReader
for this urlCon InputStream
8Socket (Client) -1
- Besides using a URLConnection, you can use a
lower level class, the Socket class, to retrieve
a web page - With the Socket class, you can connect to any
program that is listening on a port - HTTP typically listens on port 80
- FTP on port 21
- MySQL on port 3306
- SMTP on port 25
- Tomcat on port 8080
- You can write your own Java programs to
communicate with programs listening on these
ports
9Socket (Client) -2
10Socket (Client) -3
- Basic Steps Involved In Socket Programming
- Create InetAddress object for IP address/computer
(e.g. sun.com) - Create SocketAddress from this InetAddress and
Port (e.g. 80) - Create Socket and connect to SocketAddress
- Create a PrintWriter for this socket (for output)
- Create a BufferedReader for this socket (for
input) - Write some text messages to the socket (these
messages are sent to the remote program which is
listening on the port) - Read some text messages back from the socket
(this assumes that the remote program responds to
your messages)
11Socket (Client) -4
//create InetAddress object InetAddress addr
InetAddress.getByName(sun.com) int port
80 SocketAddress sockaddr new
InetSocketAddress(addr, port) // Create an
unbound socket socket new Socket() // This
method will block no more than timeoutMS // If
the timeout occurs, SocketTimeoutException is
thrown int timeoutMS 2000 socket.connect(sock
addr, timeoutMS)
12Socket (Client) -5
boolean autoflush true PrintWriter out new
PrintWriter(socket.getOutputStream(),
autoflush) InputStream inputStream
socket.getInputStream() InputStreamReader
isReader new InputStreamReader(inputStream) Buf
feredReader rd new BufferedReader(isReader) //
send our HTTP request out.println("GET
/index.html HTTP/1.1") out.println("Host
localhost80") out.println("Connection
Close") out.println() //read the response
back String s null while ((s rd.readLine())
! null) System.out.println(s) rd.close()
13Socket (Client) -6
- Socket Exceptions
- UnknownHostException
- IOException
- Imports
- java.net.
- Java.io.
14ServerSocket -1
15ServerSocket -2
- Basic Steps For Writing Server Sockets
- Create ServerSocket object for the specific port
you want to listen to (throws an Exception if
there's a problem) - Invoke ServerSocket.accept() method to block
(stop there) while waiting for connection - Get the input and output streams on that
underlying Socket - Create Printwriter and BufferedReader objects
from those streams - Read from and write to the Socket
- Close your open streams (always close the output
or writer stream BEFORE the input or reader
stream)
16ServerSocket -3
//This program waits for incoming client requests
//and when they come in, it processes them int
port 3000 //pick a port not used for anything
else ServerSocket server new ServerSocket(port)
Socket clientSocket null while (true)
//wait until client request comes (the accept()
method blocks) clientSocket server.accept()
//got a requestso process it
processRequest(clientSocket)
17ServerSocket -4
public void processRequest(Socket clientSocket)
try InputStream inputFromSocket
clientSocket.getInputStream() BufferedReader
streamReader new BufferedReader(new
InputStreamReader(inputFromSocket)) //read
one line from the client request String
clientMessage streamReader.readLine()
OutputStream outputToSocket clientSocket.getOutp
utStream() PrintWriter streamWriter new
PrintWriter(outputToSocket) //basically
just echo the request back to the client
streamWriter.println("Your request message was '"
clientMessage "'")
18ServerSocket -5
streamWriter.close() //close the writer
stream first streamReader.close()
catch (Exception e) System.out.println("E
rror handling client request " e)
19Socket Applications -1
- File Server
- Client socket connects to server and requests a
file (by supplying the file name) - Server returns contents of the file as a data
stream - Web Page Scraper
- Client socket connects to web server, requests
html document - Server returns the html document
- Client parses the document for information it
wants to write to a file or database. Information
could be email addresses, temperature readings in
an HTML table, etc.
20Socket Applications -2
- Web Page Spider/Crawler
- Client socket connects to web server, requests
html document - Server returns the html document
- Client parses the document for hyperlinks to
other pages. It stores these document links in a
file or database. - Client then creates sockets for connecting to the
web servers specified in these hyperlinks,
looking for yet more hyperlinks
21Socket Applications -3
- Meterological Information
- Client socket connects to NOAA server in
Antarctica, requests temperature at certain
location - Server reads it sensor at given location, returns
the temperature - Load Balancer
- Client socket requests information that is
obtained by running a time consuming program - Server decides which computer on a cluster has
the smallest load, and then creates its own
client socket to that computer requesting the
information - Server returns the information to the original
client
22Exercise 1
- Do a Google Search With The Socket class
- Write a program that allows you to search Google
and retrieve the results. - Here is the message/code your socket will have to
send to google on port 80 - out.println("GET /search?q" searchString "
HTTP/1.1") - out.println("Host localhost80")
- out.println("Connection Close")
- out.println() //extra println is required
- Set searchStringJavaZoneScheduleGD309 and
then wait for Googles - response and you should see the names of three
students in our class in the - html you get back from Google.
23Exercise 2
Create A Simple Web Server Your web server
should listen on port 3000 for requests for html
documents. Create a few simple web pages in your
project directory that can be retrieved by your
web server. Youll need to create a client
program that requests documents in order to test
your web server. Your request message could Be
something simple like test1.html or you can get
fancier and support directories like
/html/subdir/test1.html. Step 1 Just dump
the html you get back from web server to the
console Step 2 Load the html you get back into a
browser (Internet Explorer) Hint
Runtime.getRuntime().exec(/path/to/browser.exe
somefile.html)