URL and Socket

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

URL

Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the
protocol, authority, host name, port number, path, query, filename, and reference from a URL
using these accessor methods:
GetProtocol: Returns the protocol identifier component of the URL.
GetAuthority:Returns the authority component of the URL.
GetHost:Returns the host name component of the URL.
GetPort:Returns the port number component of the URL. The getPort method returns an integer
that is the port number. If the port is not set, getPort returns -1.
GetPath:Returns the path component of this URL.
GetQuery:Returns the query component of this URL.
GetFile:Returns the filename component of the URL. The getFile method returns the same as
getPath, plus the concatenation of the value of getQuery, if any.
GetRef:Returns the reference component of the URL.

Example:
import java.net.*;import java.io.*;
public class ParseURL { public static void main(String[] args) throws Exception { URL
aURL = new URL("http://example.com:80/docs/books/tutorial" +
"/index.html?name=networking#DOWNLOADING"); System.out.println("protocol = " +
aURL.getProtocol()); System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost()); System.out.println("port = " +
aURL.getPort()); System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery()); System.out.println("filename = " +
aURL.getFile()); System.out.println("ref = " + aURL.getRef()); }}

Socket
URLs and URLConnections provide a relatively high-level mechanism for accessing resources
on the Internet. Sometimes your programs require lower-level network communication, for
example, when you want to write a client-server application.
Note: Normally, a server runs on a specific computer and has a socket that is bound to a specific
port number. The server just waits, listening to the socket for a client to make a connection
request.
A socket is one endpoint of a two-way communication link between two programs running
on the network. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening.The client also needs to identify itself to the
server so it binds to a local port number that it will use during this connection. This is usually
assigned by the system.

If everything goes well, the server accepts the connection. 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.

On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server.
Note: Every TCP connection can be uniquely identified by its two endpoints. That way you can
have multiple connections between your host and the server.
Note: Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Java.net package has two type of class:
1. Socket: that implements one side of a two-way connection between your Java program
and another program on the network.
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this
socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this
socket.
3) public synchronized void close() closes this socket

2. ServerSocket: which implements a socket that servers can use to listen for and accept
connections to clients.
Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.

Note: If you are trying to connect to the Web, the URL class and related classes
(URLConnection, URLEncoder) are probably more appropriate than the socket classes. In fact,
URLs are a relatively high-level connection to the Web and use sockets as part of the underlying
implementation.

Client-Side writing to or reading from Socket:


This client program is straightforward and simple because the echo server implements a simple
protocol. The client sends text to the server, and the server echoes it back. When your client
programs are talking to a more complicated server such as an HTTP server, your client program
will also be more complicated. However, the basics are much the same as they are in this
program:
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol
4. Close the streams.
5. Close the socket.
Example:
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try ( Socket echoSocket = new Socket(hostName, portNumber); // 1st statement
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
// 2nd statement BufferedReader in = new BufferedReader( new
InputStreamReader(echoSocket.getInputStream())); // 3rd statement
BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in))) //
4th statement

Writing the Server Side of a Socket:

he client program is implemented by a single class, KnockKnockClient, and is very similar to the
EchoClient example from the previous section. The server program is implemented by two
classes: KnockKnockServer and KnockKnockProtocol. KnockKnockServer, which is similar to
EchoServer, contains the main method for the server program and performs the work of listening
to the port, establishing connections, and reading from and writing to the socket. The class
KnockKnockProtocol serves up the jokes. It keeps track of the current joke, the current state
(sent knock knock, sent clue, and so on), and returns the various text pieces of the joke
depending on the current state. This object implements the protocol—the language that the client
and server have agreed to use to communicate.
int portNumber = Integer.parseInt(args[0]);
try ( ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader( new
InputStreamReader(clientSocket.getInputStream()));)
{
try (
// …
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader( new
InputStreamReader(clientSocket.getInputStream()));)
{ String inputLine, outputLine; // Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null); out.println(outputLine);
while ((inputLine = in.readLine()) != null)
{
outputLine = kkp.processInput(inputLine); out.println(outputLine);
if (outputLine.equals("Bye.")) break; }

---------------------------------------------------------------------------------------------

Server.java
import java.net.*;

import java.io.*;

class MyServer{
public static void main(String args[])throws Exception{

ServerSocket ss=new ServerSocket(3333);

Socket s=ss.accept();

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){

str=din.readUTF();

System.out.println("client says: "+str);

str2=br.readLine();

dout.writeUTF(str2);

dout.flush();

din.close();

s.close();

ss.close();

}}

Client.java

import java.net.*;

import java.io.*;

class MyClient{
public static void main(String args[])throws Exception{

Socket s=new Socket("localhost",3333);

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in); String


str="",str2="";

while(!str.equals("stop")){

str=br.readLine();

dout.writeUTF(str);

dout.flush();

str2=din.readUTF();

System.out.println("Server says: "+str2);

dout.close();

s.close();

}}

What Is a Datagram?
A datagram is an independent, self-contained message sent over the network whose arrival, arrival
time, and content are not guaranteed.

• The java.net package contains three classes to help you write Java programs that use
datagrams to send and receive packets over the network: DatagramSocket,
DatagramPacket, and MulticastSocket
• An application can send and receive DatagramPackets through a DatagramSocket.
• In addition, DatagramPackets can be broadcast to multiple recipients all listening to a
MulticastSocket.
Java DatagramSocket Class:
Some Constructor:

• DatagramSocket() throws SocketEeption


• DatagramSocket(int port) throws SocketEeption
• DatagramSocket(int port, InetAddress address) throws SocketEeption

Some Method:

Method Description
void bind(SocketAddress addr) It binds the DatagramSocket to a specific
address and port.
void close() It closes the datagram socket.
void connect(InetAddress address, int port) It connects the socket to a remote address for
the socket.
void disconnect() It disconnects the socket.
boolean getBroadcast() It tests if SO_BROADCAST is enabled.
int getLocalPort() It returns the port number on the local host to
which the socket is bound.
SocketAddress getLocalSocketAddress() It returns the address of the endpoint the
socket is bound to.
int getPort() It returns the port number to which the socket
is connected.
boolean isClosed() It returns the status of socket i.e. closed or
not.
boolean isConnected() It returns the connection state of the socket.
void send(DatagramPacket p) It sends the datagram packet from the socket.
void receive(DatagramPacket p) It receives the datagram packet from the
socket.

Java DatagramPacket Class:


Some Constructor:

• DatagramPacket(byte[] barr, int length)


• DatagramPacket(byte[] barr, int length, InetAddress address, int port)

Method Description
1) InetAddress getAddress() It returns the IP address of the machine to
which the datagram is being sent or from
which the datagram was received.
2) int getPort() It returns the port number on the remote host
to which the datagram is being sent or from
which the datagram was received.
3) SocketAddress getSocketAddress() It gets the SocketAddress (IP address + port
number) of the remote host that the packet is
being sent to or is coming from.
4) void setAddress(InetAddress iaddr) It sets the IP address of the machine to which
the datagram is being sent.
5) void setData(byte[] buff) It sets the data buffer for the packet.
6) void setLength(int length) It sets the length of the packet.
7) void setPort(int iport) It sets the port number on the remote host to
which the datagram is being sent.
8) void setSocketAddress(SocketAddress It sets the SocketAddress (IP address + port
addr) number) of the remote host to which the
datagram is being sent.

Example:

Sender.java

import java.net.*;

public class DSender{

public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket();

String str = "Welcome java";

InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);

ds.send(dp);

ds.close();

} }

Reciever.java

import java.net.*;
public class DReceiver{

public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket(3000);

byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, 1024);

ds.receive(dp);

String str = new String(dp.getData(), 0, dp.getLength());

System.out.println(str);

ds.close();

} }

You might also like