Download What is Socket?

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
NETWORKING IN JAVA
java.net PACKAGE
Programming with Sockets
Developing a TCP Client
Developing a TCP Server
Client/Server Applications using UDP
Writing a Multithreaded Server
Network Application Programming Techniques
Multi-Protocol Programming using URLs
Passing Java Objects
JSSE - Java Secure Socket Extension
JavaRMI
JavaRMI Architecture
Programming with RMI
Java Sockets
 What is Socket?
 A socket is a communication endpoint
 an object through which an application sends or receives packets of data
across a network.
 The purpose is to abstract away the underlining network
 Internet protocol (IP) is a low-level routing protocol that
breaks data into small packets and send them to an address
across a network
 It does not guarantee to deliver said packages in to the destination
 Transmission Control Protocol (TCP) is a higher- level
protocol that manages to robustly string together these
packets, sorting and retransmitting them as necessary to
reliably transmit the data.
 UserDatagram Protocol (UDP) is a third protocol can be
used directly to support fast, connectionless, unreliable
transport of packets
A server runs on a specific computer and has a socket
that is bound to a specific port number.
A client makes a connection request based on the host
name of the server and the port number.
In acceptance case, the server gets a new socket
bound to a different port.
If the connection is accepted, a socket is
successfully created and the client can use the
socket to communicate with the server.
JAVA Socket Programming
 Client side
Socket
 This class implements client sockets
 A socket is an endpoint for communication between
two machines
 Server side
ServerSocket
 This class implements server sockets.
 A server socket waits for requests to come in over
the network.
 It performs some operation based on that request,
and then possibly returns a result to the requester.
Sequence of Operations for a TCP Socket
Communication
 Server
 Client
Create a server socket
Create the socket
Start listening on a port
Seek a connection
Create a new socket
Accept connection
Sending & Receiving
Sending & Receiving
Opening a Socket while
programming a client
Socket MyClient;
MyClient = new Socket ("Machine name", PortNumber);
Machine name is the machine we are trying to open a connection to
PortNumber is the port (a number) on which the server we are trying to
connect to is running.
 When selecting a port number, we should note that port
numbers between 0 and 1023 are reserved for privileged users
(that is, super user or root).
 These port numbers are reserved for standard services, such as email,
FTP, and HTTP.
 When selecting a port number for our server, we select one that is
greater than 1023
Reserved Sockets
 Once connected , a higher level protocol
proceeds, which is dependent on which we are
using
 TCP/IP reserves the lower 1024 ports for
specific protocols.
Port Number 21 is for FTP
23 is for Telnet
25 is for e-mail
79 is for finger
80 is for HTTP,
119 is for netnews.
PORT NUMBERS (last updated 2003-12-22)
 The port numbers are divided into three ranges:
 Well Known Ports are those from 0 through 1023
Registered Ports are those from 1024 through
49151
Dynamic and/or Private Ports are those from 49152
through 65535
http://www.iana.org/assignments/port-numbers
Unassigned port numbers should not be used. The
IANA will assign the number for the port after your
application has been approved
The code that opens a socket while programming a client can
be written as follows by make use of exception handling:
Socket MyClient;
try {
MyClient = new Socket("Machine
name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Opening a socket while
programming a server
ServerSocket MyService;
try {
MyService = new ServerSocket (PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
 When implementing a server we also need to create a socket object from the
ServerSocket in order to listen for and accept connections from clients.
Socket clientSocket = null;
try {
serviceSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}
Example
A client requests a single file, /index.html,
and the server relies that it has successfully
found the file and is sending it to the client
Server
Client
Listens to port 80
Accepts the connection
Connects to port 80.
Writes “GET/index.html
HTTP/1.0\n\n”.
Reads up until the
second end-of-line(\n).
Sees that Get is a known command
and that HTTP/1.0 is a valid protocol version
Reads a local file called /index.html
Writes “HTTP/1.0 200 OK \ n \ n”.
Copies the contents of the file
into the socket
Hangs up
“200” means “here comes the file”
Reads the contents of the file and displays it.
Hangs up
How do we create an input stream?
 On the client side, we can use the DataInputStream class to
create an input stream to receive response from the server:
DataInputStream input;
try {
input = new
DataInputStream(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
 The class DataInputStream allows us to read lines of text and
Java primitive data types in a portable way.
 It has methods such as read, readChar, readInt, readDouble, and
readLine,.
 We can use any function which suits our needs depending on
the type of data that we receive from the server.
How do we create an input stream?
On the server side, we can use DataInputStream to
receive input from the client:
DataInputStream input;
try {
input = new
DataInputStream(serviceSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
How do we create an output stream?
On the client side, we can create an output stream to send
information to the server socket using the class PrintStream
or DataOutputStream of java.io:
PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream());
//Returns the OutputStream associated with the invoking socket
}
catch (IOException e) {
System.out.println(e);
}
The class DataOutputStream allows us to write Java primitive
data types; many of its methods write a single Java primitive
type to the output stream. The method writeBytes is a useful
one.
How do we create an output stream?
On the server side, we can use the class
PrintStream to send information to the client.
PrintStream output;
try {
output = new
PrintStream(serviceSocket.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
How do we close sockets?
We should always close the output and input stream before you close the
socket.
 On the client side:
try {
output.close();
input.close();
MyClient.close();
}
catch (IOException e) {
System.out.println(e);
}
 On the server side:
try {
output.close();
input.close();
serviceSocket.close();
MyService.close();
}
catch (IOException e) {
System.out.println(e);
}
Client Side – Socket (summary)
Common methods
A socket can be examined at any time for the address and port information
associated with it, by use of the following methods:






getInetAddress() - Returns the address to which the
socket is connected
getInputStream() - Returns an input stream for this
socket
getOutputStream() - Returns an output stream for this
socket.
getPort() - Returns the remote port to which this socket is
connected
getLocalPort() returns the local port to which this Socket
object is connected.
close() – close this socket
Client Connection
PrintWriter
 Print formatted representations of objects to a textoutput stream.
 It does not contain methods for writing raw bytes, for
which a program should use Unicode byte streams.
BufferReader
 Read text from a character-input stream, buffering
characters so as to provide for the efficient reading of
characters, arrays, and lines
Client Side – Operation
 Client flows
 Open a socket.
 Open an input stream and
Open a socket
Open
input/output
stream
output stream to the socket.
 Read from and write to the stream
according to the server's protocol.
Send/receive data
 Close the streams.
 Close the socket.
close streams
close socket
Client Side
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter
out = null;
BufferedReader
in = null;
try {
echoSocket = new Socket (“myComputer", 7);
out = new PrintWriter (echoSocket.getOutputStream(), true);
in = new BufferedReader ( new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: myComputer.");
System.exit(1);
}
catch (IOException e) {
System.err.println ("Couldn't get I/O for " + "the connection to:
myComputer.");
System.exit(1);
}
BufferedReader
stdIn = new BufferedReader( new
InputStreamReader (System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println (userInput);
System.out.println ("echo: " + in.readLine());
}
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
Server Side
 Server flows
 create a ServerSocket
No need to bind and listen, the constructor has
already done that.
 accept a client call
 Send/Receive data
 close socket
Server Side – Example
import java.net.*;
class SimpleTCPServer
{
public static void main(String a[]) throws Exception;
{
ServerSocket acceptor = new ServerSocket (1111);
System.out.println ("On port " + acceptor.getLocalPort());
while (true)
{
Socket client = acceptor.accpet();
// Do stuff here...
client.close();
}
}
}
import java.io.*;
import java.net.*;
public class smtpClient { // smtpClient: client socket
public static void main(String[] args) {
Socket smtpSocket = null;
DataOutputStream os = null ;//os: output stream
DataInputStream is = null; // is: input stream
// Initialization section:
// Try to open a socket on port 25
// Try to open input and output streams
try {
smtpSocket = new Socket ("hostname", 25)
os = new
DataOutputStream(smtpSocket.getOutputStream());
is = new
DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host:
hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the
connection to: hostname");
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 25
if (smtpSocket != null && os != null && is != null) {
try {
// The capital string before each colon has a special meaning to SMTP
// you may want to read the SMTP specification, RFC1822/3
os.writeBytes("HELO\n");
os.writeBytes("MAIL From: [email protected]\n");
os.writeBytes("RCPT To: [email protected]\n");
os.writeBytes("DATA\n");
os.writeBytes("From: [email protected]\n");
os.writeBytes("Subject: testing\n");
os.writeBytes(“Okey \n"); // message body
os.writeBytes("\n.\n");
os.writeBytes("QUIT");
// keep on reading from/to t he socket till we receive the "Ok" from SMTP,
// once we received that then we want to break.
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println ("Server: " + responseLine);
if (responseLine.indexOf ("Ok") != -1) {
break;
}
}
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown
host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
Echo server
 Now let's write a server. This
 server is very similar to the echo server running on




port7.
Basically, the echo server receives text from the
client and then sends that exact text back to the
client.
This is just about the simplest server we can write.
Note that this server handles only one client.
We can modify it to handle multiple clients using
threads.
import java.io.*;
import java.net.*;
public class echo3 {
public static void main(String args[]) {
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket (9999);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
//Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
URLConnection
Creating a URL
try {
// With components.
URL url = new URL("http", "hostname", 80,
"index.html");
// With a single string.
url = new,
URL("http://hostname:80/index.html"); } ,
catch (MalformedURLException e) { }
Getting Text from a URL
try {
// Create a URL for the desired page
URL url = new URL("http://hostname:80/index.html");
// Read all the text returned by the server BufferedReader in =
new BufferedReader (new InputStreamReader
(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text;
// readLine() strips the newline character(s) }
in.close(); }
catch (MalformedURLException e) { }
catch (IOException e) { }
Getting an Image from a URL
try {
// Create a URL for the image's location URL
url = new URL("http://hostname:80/image.gif");
// Get the image
java.awt.Image image =
java.awt.Toolkit.getDefaultToolkit().createImage(url);
}
catch (MalformedURLException e) { }
catch (IOException e) { }
Reference Web Links
Socket programming
http://java.sun.com/docs/books/tutorial/networking/
SMTP protocol:
http://www.ietf.org/rfc/rfc821.txt
Java Remote Method Invocation (Java
RMI)
 Java RMI enables the programmer to create
distributed Java technology-based to Java
technology-based applications
 the methods of remote Java objects can be invoked
from other Java virtual machines, possibly on different
hosts.
 RMI uses object serialization to marshal and
unmarshal parameters and does not truncate
types, supporting true object-oriented
polymorphism
http://abra.sourceforge.net/doc/javadoc/org/ephma
n/abra/tools/Marshaller.html