Docsity

Socket Programming in Java-Jave Programming-Lecture Slides, Slides of Java Programming

Partial preview of the text

Download Socket Programming in Java-Jave Programming-Lecture Slides and more Slides Java Programming in PDF only on Docsity!

Socket^ Programming

in^ Java docsity.com

Learning^ Objectives • The InetAddress^ Class • Using sockets – TCP sockets – Datagram^ Sockets

Exceptions^ in

Java

•^ BindException •^ ConnectException •^ MalformedURLException •^ NoRouteToHostException •^ ProtocolException •^ SocketException •^ UnknownHostException •^ UnknownServiceException

Socket^ Programming

in^ Java

// Sender public^ static^ void^ main(String[]

args) { int^ remotePort^ =^ 30000;DatagramSocket^ socket^ =^ null;DatagramPacket^ packet^ =^ null;InetAddress^ ipAddr^ =^ null; try{socket^ =^ new^ DatagramSocket();}catch^ (SocketException^ ex)^ {}^ try^ { ipAddr=InetAddress.getLocalHost();}^ catch^ (UnknownHostException

for (int i = 0; i < 5; i++) {String msg = “Messagenumber: "+ i;byte [] data =msg.getBytes();packet = newDatagramPacket(data,data.length, ipAddr,remotePort);try { socket.send(packet); } ex) {}catch (IOException e) {}} // for} // main

Datagram^ SocketsSERVER:1. Create a DatagramSocket^ object DatagramSocket^ dgramSocket^ = new^ DatagramSocket(1234); 2. Create a buffer^ for^ incoming^ datagrams byte[] buffer^ =^ new^ byte[256]; 3. Create a DatagramPacket^ object^ for

the^ incoming^ datagram DatagramPacket^ inPacket^ =^ new^ DatagramPacket(buffer,

buffer.length);

4.^ Accept^ an^ incoming

datagram dgramSocket.receive(inPacket)

Datagram^ SocketsSERVER:5. Accept the sender’s^ address^ and^ port^ from

the^ packet InetAddress^ clientAddress

=^ inPacket.getAddress(); int^ clientPort^ =^ inPacket.getPort(); 6. Retrieve^ the^ data^ from^ the

buffer string^ message^ =^ new^ String(inPacket.getData(),

0,^ inPacket.getLength());

7.^ Create^ the^ response datagram^ DatagramPacket^ outPacket

= new DatagramPacket(response.getBytes(),

response.length(),^ clientAddress,

clientPort);

8.^ Send^ the^ response^ datagram^ dgramSocket.send(outPacket) 9.^ Close^ the^ DatagramSocket:

dgram.close();

Datagram^ SocketsCLIENT:5. Create a DatagramPacket^ object

for^ the^ incoming

datagram^ DatagramPacket inPacket =^ new^ DatagramPacket(buffer,

buffer.length);

6.^ Accept^ an^ incoming

datagram

dgramSocket.receive(inPacket) 7. Retrieve^ the^ data^ from

the^ buffer

string^ response^ =^ new

String(inPacket.getData(),

inPacket.getLength()); 8. Close^ the^ DatagramSocket:^ dgram.close();

The^ InetAddress

Class

-^ Handles^ Internet^ addresses

both^ as^ host^ names^ and

as^ IP addresses • Static^ Method^ getByName

returns^ the^ IP^ address^

of^ a specified^ host^ name^ as

an^ InetAddress^ object

-^ Methods^ for^ address/name

conversion: public^ static^ InetAddress^ getByName(String

host)^ throws^ UnknownHostException public^ static^ InetAddress[]^ getAllByName(String

host)^ throws^ UnknownHostException public^ static^ InetAddress^ getLocalHost()

throws^ UnknownHostException public^ boolean^ isMulticastAddress()public^ String^ getHostName()public^ byte[]^ getAddress()public^ String^ getHostAddress()public^ int^ hashCode()public^ boolean^ equals(Object^ obj)public^ String^ toString()

Retrieving^ the^ current

machine’s^ address import java.net.*;public class MyLocalIPAddress{ public static void main(String[] args){ try{ InetAddress address =InetAddress.getLocalHost();System.out.println (address);} catch (UnknownHostException e){ System.out.println("Could not find localaddress!");} } }

The^ Java.net.Socket

Class

-^ Connection^ is^ accomplished

through^ the^ constructors.

Each Socket^ object^ is^ associated

with^ exactly^ one^ remote

host.^ To connect^ to^ a^ different^ host,

you^ must^ create^ a^ new

Socket object.public^ Socket(String^ host,

int^ port)^ throws^ UnknownHostException, IOExceptionpublic Socket(InetAddress^ address,^ int^ port)^ throws^ IOExceptionpublic Socket(String host, int^ port,^ InetAddress^ localAddress,

int^ localPort) throws^ IOExceptionpublic^ Socket(InetAddress^ address,

int^ port,^ InetAddress^ localAddress,

int localPort)^ throws^ IOException • Sending^ and^ receiving^ data^ is^ accomplished

with^ output^ and^ input streams.^ There^ are^ methods

to^ get^ an^ input^ stream^ for^

a^ socket^ and^ an output^ stream^ for^ the^ socket

. public InputStream getInputStream()^ throws

IOException public^ OutputStream^ getOutputStream()

throws IOException • There's a^ method^ to^ close^ a^ socket: public^ void^ close()^ throws

IOException

Simple^ Client

‐Server^ Example response Client Serverrequestsocket()bind()socket()listen()Connectionconnect()accept()establishmentsend()Data requestrecv()send()Data responserecv()close()recv()End-of-file notificationclose()

TCP^ SocketsSERVER:1. Create a ServerSocket^ object ServerSocket servSocket^ =^ new^ ServerSocket(1234); 2. Put the server^ into^ a^ waiting^

state

Socket^ link^ =^ servSocket.accept(); 3. Set^ up^ input^ and^

output^ streams

4. Send^ and^ receive

data

out.println(awaiting

data…);

String^ input^ =^ in.readLine(); 5. Close^ the^ connection link.close()

TCP^ Sockets CLIENT:1. Establish a connection^ to^ the^

server Socket^ link^ =^ new Socket(inetAddress.getLocalHost(),1234); 2. Set^ up^ input^ and^

output^ streams

  1. Send^ and^ receive

data

  1. Close^ the^ connection

TCP^ Connections • A TCP connection^ is^ between

a^ Client^ Host^ and

a^ Server^ Host • The^ Server^ is^ passive;

It^ just^ waits

•^ The^ Client^ is^ active •^ More^ than^ one

connection^ is^ allowed

between

to^ hosts • TCP^ connections^

are^4 ‐tuples – {<src‐host,src‐port>,<dst‐host,dst‐port>}