0% found this document useful (0 votes)
11 views45 pages

Java Socket Programming Basics

The document provides an overview of Java Socket Programming, detailing classes such as InetAddress, Socket, ServerSocket, and DatagramSocket. It explains TCP and UDP socket communication, including sample client-server applications and methods for sending and receiving data. Additionally, it covers the URL class for handling web resources and retrieving content from URLs.

Uploaded by

fussymint
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views45 pages

Java Socket Programming Basics

The document provides an overview of Java Socket Programming, detailing classes such as InetAddress, Socket, ServerSocket, and DatagramSocket. It explains TCP and UDP socket communication, including sample client-server applications and methods for sending and receiving data. Additionally, it covers the URL class for handling web resources and retrieving content from URLs.

Uploaded by

fussymint
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Java Socket Programming

Java Sockets Programming


 The package [Link] provides support
for sockets programming (and more).

 Typically you import everything defined


in this package with:

import [Link].*;

Java Socket Programming 2


Classes
InetAddress

Socket

ServerSocket

DatagramSocket

DatagramPacket

Java Socket Programming 3


InetAddress class
 static methods you can use to create new
InetAddress objects.
 getByName(String host)
 getAllByName(String host)
 getLocalHost()

InetAddress x = [Link](

“[Link]”);
 Throws UnknownHostException

Java Socket Programming 4


Sample Code: [Link]
 Uses InetAddress class to lookup hostnames
found on command line.

> java Lookup [Link] [Link]


[Link]:[Link]
[Link]:[Link]

Java Socket Programming 5


try
try {{

InetAddress
InetAddress aa == [Link](hostname);
[Link](hostname);

[Link](hostname
[Link](hostname ++ ":"
":" ++
[Link]());
[Link]());

}} catch
catch (UnknownHostException
(UnknownHostException e)
e) {{

[Link]("No
[Link]("No address
address found
found for
for "" ++
hostname);
hostname);

}}

Java Socket Programming


Socket class
 Corresponds to active TCP sockets only!
 client sockets
 socket returned by accept();

 Passive sockets are supported by a


different class:
 ServerSocket

 UDP sockets are supported by


 DatagramSocket

Java Socket Programming 7


JAVA TCP Sockets
 [Link]
 Implements client sockets (also called just “sockets”).
 An endpoint for communication between two machines.
 Constructor and Methods
• Socket(String host, int port): Creates a stream socket and connects it to the specified
port number on the named host.
• InputStream getInputStream()
• OutputStream getOutputStream()
• close()

 [Link]
 Implements server sockets.
 Waits for requests to come in over the network.
 Performs some operation based on the request.
 Constructor and Methods
• ServerSocket(int port)
• Socket Accept(): Listens for a connection to be made to this socket and accepts it. This
method blocks until a connection is made.

Java Socket Programming 8


Sockets

Client socket, welcoming socket (passive) and connection socket (active)

Java Socket Programming 9


Socket Constructors
 Constructor creates a TCP connection to a
named TCP server.
 There are a number of constructors:

Socket(InetAddress server, int port);

Socket(InetAddress server, int port,


InetAddress local, int
localport);

Socket(String hostname, int port);

Java Socket Programming 10


Socket Methods
void close();
InetAddress getInetAddress();
InetAddress getLocalAddress();
InputStream getInputStream();
OutputStream getOutputStream();

 Lots more (setting/getting socket options,


partial close, etc.)

Java Socket Programming 11


Socket I/O
 Socket I/O is based on the Java I/O support
 in the package [Link]

 InputStream and OutputStream are


abstract classes
 common operations defined for all kinds of
InputStreams, OutputStreams…

Java Socket Programming 12


InputStream Basics
// reads some number of bytes and
// puts in buffer array b
int read(byte[] b);

// reads up to len bytes


int read(byte[] b, int off, int len);

Both methods can throw IOException.


Both return –1 on EOF.
Java Socket Programming 13
OutputStream Basics

// writes [Link] bytes


void write(byte[] b);

// writes len bytes starting


// at offset off
void write(byte[] b, int off, int len);

Both methods can throw IOException.

Java Socket Programming 14


ServerSocket Class
(TCP Passive Socket)
 Constructors:

ServerSocket(int port);

ServerSocket(int port, int backlog);

ServerSocket(int port, int backlog,


InetAddress bindAddr);

Java Socket Programming 15


ServerSocket Methods
Socket accept();

void close();

InetAddress getInetAddress();

int getLocalPort();

throw IOException, SecurityException

Java Socket Programming 16


Socket programming with
TCP
keyboard monitor

Example client-server
app:

inFromUser
input
 client reads line from stream

standard input (inFromUser Client


Process Input stream:
stream) , sends to server via process sequence of
socket (outToServer output stream: bytes
stream) sequence of bytes into process
 server reads line from socket out of process
 server converts line to

inFromServer
outToServer
output input
stream stream
uppercase, sends back to
client
client TCP
 client reads, prints modified clientSocket
socket TCP
line from socket socket

(inFromServer stream) to network from network

Java Socket Programming 17


Client/server socket interaction:
TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection requestconnection setup connect to hostid, port=x
connectionSocket = clientSocket =
[Link]() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
Java Socket Programming 18
[Link]
import [Link].*;
import [Link].*;

class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;

BufferedReader inFromUser =
new BufferedReader(new
InputStreamReader([Link]));

Socket clientSocket = new Socket("hostname",


6789);

DataOutputStream outToServer =
new DataOutputStream([Link]());
[Link]
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader([Link]()));

sentence = [Link]();

[Link](sentence + '\n');

modifiedSentence = [Link]();

[Link]("FROM SERVER: " +


modifiedSentence);

[Link]();
}
}
Java Socket Programming 20
[Link]
import [Link].*;
import [Link].*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;

ServerSocket welcomeSocket = new


ServerSocket(6789);

while(true) {

Socket connectionSocket =
[Link]();

BufferedReader inFromClient = new BufferedReader(new

InputStreamReader([Link]()));
[Link]

DataOutputStream outToClient =
new
DataOutputStream([Link]());

clientSentence = [Link]();

capitalizedSentence = [Link]() + '\n';

[Link](capitalizedSentence);

}
}
}

Java Socket Programming 22


Sample Echo Server
[Link]

Simple TCP Echo server.

Based on code from:


TCP/IP Sockets in Java

Java Socket Programming 23


UDP Sockets
 DatagramSocket class

 DatagramPacket class needed to specify


the payload
 incoming or outgoing

Java Socket Programming 24


Socket Programming with
UDP
 UDP
 Connectionless and unreliable service.
 There isn’t an initial handshaking phase.
 Doesn’t have a pipe.
 transmitted data may be received out of order, or lost

 Socket Programming with UDP


 No need for a welcoming socket.
 No streams are attached to the sockets.
 the sending hosts creates “packets” by attaching the IP
destination address and port number to each batch of bytes.
 The receiving process must unravel to received packet to
obtain the packet’s information bytes.

Java Socket Programming 25


JAVA UDP Sockets
 In Package [Link]
 [Link]
• A socket for sending and receiving datagram
packets.
• Constructor and Methods
– DatagramSocket(int port): Constructs a
datagram socket and binds it to the specified
port on the local host machine.
– void receive( DatagramPacket p)
– void send( DatagramPacket p)
– void close()

Java Socket Programming 26


DatagramSocket
Constructors
DatagramSocket();

DatagramSocket(int port);

DatagramSocket(int port, InetAddress a);

All can throw SocketException or


SecurityException

Java Socket Programming 27


Datagram Methods
void connect(InetAddress, int port);

void close();

void receive(DatagramPacket p);

void send(DatagramPacket p);

Lots more!

Java Socket Programming 28


Datagram Packet
 Contain the payload
 (a byte array

 Can also be used to specify the


destination address
 when not using connected mode UDP

Java Socket Programming 29


DatagramPacket
Constructors
For receiving:

DatagramPacket( byte[] buf, int len);

For sending:

DatagramPacket( byte[] buf, int len


InetAddress a, int
port);

Java Socket Programming 30


DatagramPacket methods
byte[] getData();
void setData(byte[] buf);

void setAddress(InetAddress a);


void setPort(int port);

InetAddress getAddress();
int getPort();

Java Socket Programming 31


Example: Java client (UDP)
keyboard monitor

inFromUser
input
stream

Client
Process
Input: receives
process
packet (TCP
received “byte
Output: sends
stream”)
packet (TCP sent

receivePacket
sendPacket
“byte stream”) UDP UDP
packet packet

client UDP
clientSocket
socket UDP
socket

to network from network

Java Socket Programming 32


Client/server socket interaction:
UDP
Server (running on hostid) Client

create socket,
port=x, for create socket,
clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket

write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port umber close
clientSocket

Java Socket Programming 33


[Link]
import [Link].*;
import [Link].*;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader([Link]));
DatagramSocket clientSocket = new
DatagramSocket();
InetAddress IPAddress =
[Link]("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = [Link]();
sendData = [Link]();
[Link]
DatagramPacket sendPacket =
new DatagramPacket(sendData,
[Link], IPAddress, 9876);
[Link](sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
[Link]);
[Link](receivePacket);
String modifiedSentence =
new String([Link]());
[Link]("FROM SERVER:" + modifiedSentence);

[Link]();
}
}
Java Socket Programming 35
[Link]
import [Link].*;
import [Link].*;

class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new
DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
[Link]);
[Link](receivePacket);
String sentence = new String([Link]());
[Link]

InetAddress IPAddress = [Link]();


int port = [Link]();
String capitalizedSentence = [Link]();
sendData = [Link]();
DatagramPacket sendPacket =
new DatagramPacket(sendData, [Link], IPAddress,
port);
[Link](sendPacket);

}
}
}

Java Socket Programming 37


Sample UDP code
[Link]

Simple UDP Echo server.

Test using nc as the client (netcat):


> nc –u hostname port

Java Socket Programming 38


Socket functional calls
 socket (): Create a socket
 bind(): bind a socket to a local IP address and port #

 listen(): passively waiting for connections


 connect(): initiating connection to another socket
 accept(): accept a new connection

 Write(): write data to a socket


 Read(): read data from a socket
 sendto(): send a datagram to another UDP socket
 recvfrom(): read a datagram from a UDP socket

 close(): close a socket (tear down the connection)

Java Socket Programming 39


Java URL Class
 Represents a Uniform Resource Locator
 scheme (protocol)
 hostname
 port
 path
 query string

Java Socket Programming 40


Parsing

 You can use a URL object as a parser:

URL u = new URL(“[Link]

[Link](“Proto:” + [Link]());

[Link](“File:” + [Link]());

Java Socket Programming 41


URL construction
 You can also build a URL by setting each part
individually:

URL u = new URL(“http”,

[Link],80,”/~mgunes/”);

[Link](“URL:” + [Link]());

[Link](“URL: “ + u);

Java Socket Programming 42


Retrieving URL contents
 URL objects can retrieve the documents they refer
to!
 actually this depends on the protocol part of the URL.
 HTTP is supported
 File is supported (“[Link]
 You can get “Protocol Handlers” for other protocols.

 There are a number of ways to do this:

Object getContent();

InputStream openStream();

URLConnection openConnection();

Java Socket Programming 43


Getting Header Information
 There are methods that return information
extracted from response headers:
String getContentType();
String getContentLength();
long getLastModified();

Java Socket Programming 44


URLConnection
 Represents the connection (not the URL itself).

 More control than URL


 can write to the connection (send POST data).
 can set request headers.

 Closely tied to HTTP

Java Socket Programming 45

You might also like