Java Network Programming getting started, Getting Started with java network programming, two tier architecture, java client server programming, core java, java to standard edition, core java, Introduction to network programming in java
Network programming in java - PPT with Easy Programs and examples of Java InetAddress Class and java socket programming example.
Learn more @ http://java2all.com/technology/network-programming
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Network programming in java - PPT with Easy Programs and examples of Java InetAddress Class and java socket programming example.
Learn more @ http://java2all.com/technology/network-programming
The presentation given at MSBTE sponsored content updating program on 'Advanced Java Programming' for Diploma Engineering teachers of Maharashtra. Venue: Guru Gobind Singh Polytechnic, Nashik
Date: 22/12/2010
Session: Java Network Programming
Java- Datagram Socket class & Datagram Packet classRuchi Maurya
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
________________________________________
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.
________________________________________
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.
The Presentation given at Guru Gobind Singh Polytechnic, Nashik for Third Year Information Technology and Computer Engineering Students on 08/02/2011.
Topic: Java Network Programming
This presentation introduces basic concepts about the Java socket abstraction. These slides introduce the following concepts:
- What is a socket
- How to implement a client program
- How to implement a server program
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
java, getting started with java code security, getting started with java document security, core java, j2se, introduction to code security, introduction to document security, java code and document security
Introduction to java beans, java beans, Core java, j2se, getting started with java beans programming, java to standard edition, beans in java, beans programming in java
Java- Datagram Socket class & Datagram Packet classRuchi Maurya
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
________________________________________
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.
________________________________________
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.
The Presentation given at Guru Gobind Singh Polytechnic, Nashik for Third Year Information Technology and Computer Engineering Students on 08/02/2011.
Topic: Java Network Programming
This presentation introduces basic concepts about the Java socket abstraction. These slides introduce the following concepts:
- What is a socket
- How to implement a client program
- How to implement a server program
The presentation is took from the Java course I run in the bachelor-level informatics curriculum at the University of Padova.
java, getting started with java code security, getting started with java document security, core java, j2se, introduction to code security, introduction to document security, java code and document security
Introduction to java beans, java beans, Core java, j2se, getting started with java beans programming, java to standard edition, beans in java, beans programming in java
A bean is a reusable software component based on Sun's JavaBeans specification that can be manipulated visually in a builder tool.“
The JavaBeans technology enables vendors to create environments that make it dramatically easier to develop user interfaces for Java applications.
Java programming, Java Swing Programming, SWING GUI Design, desktop application, Getting Started with Swing application development in java, Introduction to GUI based programming in java, Java to standard edition, J2SE, Core Java, Swing package in java
This is all about socket programming in java using TCP and UDP socket and an example of simple Echo Server.
Also includes concepts of the socket, Socket class and methods and use of those.
Java D&D, Java File Transfer, Java programming, j2se, java to standard edition, java drag and drop, D&D in java, Getting started with D&D in java, Java Data Transfer, JAVA API, Core java
Remote Method Invocation, Distributed Programming in java, Java Distributed Programming, Network Programming in JAVA, Core Java, Introduction to RMI, Getting Started with RMI, Getting Started with Remote Method Invocation, Distributed Programming, Java, J2SE
Java to database connectivity for beginners, Introduction to JDBC, Getting Started with java database programming, What is java database?, core java, java to standard edition, core java, java
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
3. ADVANCE JAVA
Author Profile
Ankit Desai
Ph.D. Scholar, IET, Ahmedabad University
Education: M. Tech. (C.E.), B. E. (I. T.)
Experience: 8 years (Academic and Research)
Research Interest: IoT, Big Data Analytics, Machine
Learning, Data Mining, Algorithms.
Classified e-Material 3
4. ADVANCE JAVA
Classified e-Material 4
InetAddress CLASS
The Inetaddress class provides you with a limited
interface to DNS for doing both forward and
reverse internet address lookups
An InetAddress class method corresponds to a DNS
request
5. ADVANCE JAVA
Classified e-Material 5
InetAddress CLASS
No public constructor
Static methods:
static InetAddress[] getAllByName (String host)
Static method used to retrieve all the addresses for the
host name passed as a parameter.
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
static InetAddress getByAddress (String host,
byte[] addr)
Create an InetAddress based on the provided host name
and IP address No name service is checked for the validity
of the address.
6. ADVANCE JAVA
Classified e-Material 6
static InetAddress getByName(String)
Static method used to retrieve the address for the host
name passed as the parameter.
static InetAddress getLocalHost( )
Static method used to retrieve the address for the
current, or local, host.
7. ADVANCE JAVA
Classified e-Material 7
InetAddress Class
Additional “getter” methods
byte[ ] getAddress()
Returns the IP address.
String getHostAddress()
Returns the IP address as a string.
String getHostName()
Returns the host name.
9. ADVANCE JAVA
Classified e-Material 9
TCP Sockets
Once a TCP socket connection is made, a virtual
stream is in place. Java’s IO model is that of a stream,
therefore the models are consistent; all you need to do
connect a TCP socket to a stream and read and write
the streams.
10. ADVANCE JAVA
Classified e-Material 10
JAVA TCP Sockets
In Package java.net
java.net.Socket
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()
11. ADVANCE JAVA
Classified e-Material 11
java.net.ServerSocket
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.
12. ADVANCE JAVA
Classified e-Material 12
Socket Class - TCP Client sockets
Socket(String ip, int port)
Creates a streaming socket and binds it to the host and
port specified as parameters.
Socket(String ip, int port, boolean TCPorUDP)
Creates a socket and binds it to the host and port
specified as parameters. The last parameter is used to
indicate whether the socket should be a stream or
datagram socket.
Socket(InetAddress ia, int port)
Creates a streaming socket connected to the specified
host and port.
Socket(InetAddress ia, int port, boolean TCPorUDP)
Creates a socket connected to the specified host and
port. The last parameter specifies whether the socket
should be a stream or datagram socket.
13. ADVANCE JAVA
Classified e-Material 13
Client Sockets (Methods)
InetAddress getInetAddress( )
Returns the address to which the socket is connected
int getPort( )
Returns the port number on the remote host for this
socket
InetAddress getLocalAddress( )
Gets the local address to which the socket is bound.
int getLocalPort( )
Returns the port number on the local host for this
socket.
InputStream getInputStream( )
Returns an input stream for the socket.
OutputStream getOutputStream( )
Returns an output stream for the socket.
void close()
Closes the socket.
14. ADVANCE JAVA
Classified e-Material 14
Client Sockets (Methods)
int GetSoLinger()
void setSoLinger(boolean on, int linger)
This option sets how long a socket is remain open
after a close() method has been invoked and data
remains to be sent over the socket
public int getSoTimeout()
public void setSoTimeout(int timeout)
this option set to a non-zero timeout, a read() call on
the InputStream associated with this Socket will block
for only this amount of time
15. ADVANCE JAVA
Classified e-Material 15
Client Sockets (Methods)
public void setTcpNoDelay(boolean on)
public boolean getTcpNoDelay()
Option is used to specify Nagle’s algorithm should
be used to buffer data that is sent over a socket
connection.
16. ADVANCE JAVA
Classified e-Material 16
ServerSocket class- Constructors
public ServerSocket(int port) throws IOException
Creates a server socket, bound to the specified port.
public ServerSocket(int port, int backlog) throws
IOException
Creates a server socket and binds it to the specified local
port number, with the specified backlog.
public ServerSocket(int port, int backlog, InetAddress
networkInterface) throws IOException
Create a server with the specified port, listen backlog,
and local IP address to bind to.
17. ADVANCE JAVA
Classified e-Material 17
ServerSocket class- Methods
public Socket accept() throws IOException
Listens for a connection to be made to this socket and
accepts it. The method blocks until a connection is
made
public void close() throws IOException
Closes this socket. Any thread currently blocked in
accept() will throw a SocketException
public InetAddress getInetAddress()
Returns the local address of this server socket
public void bind(SocketAddress endpoint) throws
IOException
Binds the ServerSocket to a specific address (IP
address and port number)
18. ADVANCE JAVA
Classified e-Material 18
ServerSocket class- Methods
public int getLocalPort()
Returns the port on which this socket is listening.
public SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound
to, or null if it is not bound yet.
protected final void implAccept(Socket s) throws
IOException
Subclasses of ServerSocket use this method to override
accept() to return their own subclass of socket.
public boolean isBound()
Returns the binding state of the ServerSocket.
public boolean isClosed()
Returns the closed state of the ServerSocket
19. ADVANCE JAVA
Classified e-Material 19
ServerSocket class- Methods
public void setSoTimeout(int timeout) throws
SocketException
Enable/disable SO_TIMEOUT with the specified timeout,
in milliseconds. With this option set to a non-zero
timeout, a call to accept() for this ServerSocket will
block for only this amount of time. If the timeout
expires, a java.net.SocketTimeoutException is
raised, though the ServerSocket is still valid
public int getSoTimeout() throws IOException
Retrive setting for SO_TIMEOUT. 0 returns implies that
the option is disabled
public void setReuseAddress(boolean on) throws
SocketException
Enable/disable the SO_REUSEADDR socket option
21. ADVANCE JAVA
Classified e-Material 21
Implementing a Server
1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream());
os = new DataOutputStream( client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hellon");
5. Close sockets: client.close();
22. ADVANCE JAVA
Classified e-Material 22
For multithreaded server:
while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as
parameter (the thread creates streams (as in
step (3) and does communication as stated in
(4). Remove thread once service is provided.
}
23. ADVANCE JAVA
Classified e-Material 23
Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server:
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream(client.getOutputStream() );
3. Perform I/O or communication with the server:
Receive data from the server:
String line = is.readLine();
Send data to the server:
os.writeBytes("Hellon");
4. Close the socket when done:
client.close();
26. ADVANCE JAVA
Classified e-Material 26
UDP Sockets
Since UDP is a connectionless protocol; there is no
virtual stream between the hosts so streams are not
used for IO.
UDP applications are not thought of in terms of
clients and servers, but rather in terms of senders
and receivers.
For conversational applications both ends (sender
and receiver) will be changing states from sender to
receiver and back again
Many UDP based applications are simple send a
request then receive the data (sender’s perspective),
like a DNS request. The receiver’s perspective is to
‘listen’ for a request, send the response, listen for
more requests.
27. ADVANCE JAVA
Classified e-Material 27
DatagramPacket Class
UDP sockets send and receive Datagrams
Constructors: two for receiving, four for sending
DatagramPacket( byte[ ] buff , int len)
Constructs a DatagramPacket for receiving packets of
length len.
DatagramPacket(byte[] buf, int off, int len)
Constructs a DatagramPacket for receiving packets of
length len, specifying an offset of off bytes into the buffer.
DatagramPacket((byte[] buf, int len, InetAddress addr,
int port)
Constructs a datagram packet for sending packets of
length len to the specified port number on the specified
host.
28. ADVANCE JAVA
Classified e-Material 28
DatagramPacket(byte[] buf, int off, int len,
SocketAddress addr)
Constructs a datagram packet for sending packets of
length len with offset off to the specified port number
on the specified host.
DatagramPacker(byte[] buf, int off, int len,
InetAddress addr, int port)
Constructs a datagram packet for sending packets of
length len with offset off to the specified port number
on the specified host.
29. ADVANCE JAVA
Classified e-Material 29
DatagramPacket Class- Methods
public InetAddress getAddress()
Returns the IP address of the machine to which this
datagram is being sent or from which the datagram
was received.
public int getPort()
Returns the port number on the remote host to which
this datagram is being sent or from which the
datagram was received.
public byte[] getData()
Returns the data buffer. The data received or the data
to be sent starts from the offset in the buffer, and runs
for length long.
public int getOffset()
Returns the offset of the data to be sent or the offset
of the data received.
30. ADVANCE JAVA
Classified e-Material 30
DatagramPacket Class- Methods
public int getLength()
Returns the length of the data to be sent or the
length of the data received.
public void setData(byte[] buf, int offset, int length)
Set the data buffer for this packet. This sets the
data, length and offset of the packet.
public void setAddress(InetAddress iaddr)
Sets the IP address of the machine to which this
datagram is being sent.
public void setPort(int iport)
Sets the port number on the remote host to which
this datagram is being sent.
31. ADVANCE JAVA
Classified e-Material 31
DatagramPacket Class- Methods
public void
setSocketAddress(SocketAddress address)
Sets the SocketAddress (usually IP address + port
number) of the remote host to which this datagram
is being sent.
public SocketAddress getSocketAddress()
Gets the SocketAddress (usually IP address + port
number) of the remote host that this packet is
being sent to or is coming from.
public void setData(byte[] buf)
Set the data buffer for this packet. With the offset
of this DatagramPacket set to 0, and the length set
to the length of buf.
32. ADVANCE JAVA
Classified e-Material 32
public void setLength(int length)
Set the length for this packet. The length of the
packet is the number of bytes from the packet's data
buffer that will be sent, or the number of bytes of the
packet's data buffer that will be used for receiving
data. The length must be lesser or equal to the offset
plus the length of the packet's buffer.
33. ADVANCE JAVA
Classified e-Material 33
DatagramSocket Class – UDP Sockets
Constructors
DatagramSocket()
Constructs a datagram socket and binds it to any available port
on the local host.
DatagramSocket(DatagramSocketImpl impl)
Creates an unbound datagram socket with the specified
DatagramSocketImpl.
DatagramSocket(int port)
Constructs a datagram socket and binds it to the specified port
on the local host.
DatagramSocket(int port, InetAddress iaddr)
Creates a datagram socket, bound to the specified local
address.
DatagramSocket(SocketAddress bindaddr)
Creates a datagram socket, bound to the specified local socket
address.
34. ADVANCE JAVA
Classified e-Material 34
DatagramSocket Class –Methods
public void bind(SocketAddress addr) throws
SocketException
Binds this DatagramSocket to a specific address &
port.
public void connect(InetAddress address, int port)
Connects the socket to a remote address for this
socket.
public void connect(SocketAddress addr) throws
SocketException
Connects this socket to a remote socket address (IP
address + port number).
public void disconnect()
Disconnects the socket. This does nothing if the
socket is not connected.
35. ADVANCE JAVA
Classified e-Material 35
DatagramSocket Class –Methods
public boolean isBound()
Returns the binding state of the socket.
public boolean isConnected()
Returns the connection state of the socket.
public InetAddress getInetAddress()
Returns the address to which this socket is
connected. Returns null if the socket is not
connected.
public int getPort()
Returns the port for this socket. Returns -1 if the
socket is not connected.
36. ADVANCE JAVA
Classified e-Material 36
DatagramSocket Class –Methods
public SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint this socket is
connected to, or null if it is unconnected.
public SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is
bound to, or null if it is not bound yet.
public void send(DatagramPacket p) throws
IOException
Sends a datagram packet from this socket.
public void receive(DatagramPacket p) throws
IOException
Receives a datagram packet from this socket.
37. ADVANCE JAVA
Classified e-Material 37
DatagramSocket Class –Methods
public InetAddress getLocalAddress()
Gets the local address to which the socket is bound
public int getLocalPort()
Returns the port number on the local host to which
this socket is bound
public void setSoTimeout(int timeout) throws
SocketException
Enable/disable SO_TIMEOUT with the specified
timeout, in milliseconds
public int getSoTimeout() throws SocketException
Retrive setting for SO_TIMEOUT. 0 returns implies
that the option is disabled
38. ADVANCE JAVA
Classified e-Material 38
DatagramSocket Class –Methods
public void setSendBufferSize(int size) throws
SocketException
Sets the SO_SNDBUF option to the specified value for
this DatagramSocket
public int getSendBufferSize() throws
SocketException
Get value of the SO_SNDBUF option for this
DatagramSocket, that is the buffer size used by the
platform for output on this DatagramSocket
public void setReceiveBufferSize(int size) throws
SocketException
Sets the SO_RCVBUF option to the specified value for
this DatagramSocket
public int getReceiveBufferSize() throws
SocketException
Get value of the SO_RCVBUF option for this
DatagramSocket, that is the buffer size used by the
platform for input on this DatagramSocket
39. ADVANCE JAVA
Classified e-Material 39
Multicast Example
DatagramSocket socket = new DatagramSocket();
byte[] b = new byte[DGRAM_LENGTH];
DatagramPacket dgram;
dgram = new DatagramPacket(b, b.length,
InetAddress.getByName(MCAST_ADDR), DEST_PORT);
System.err.println("Sending " + b.length + " bytes to " +
dgram.getAddress() + ':' + dgram.getPort());
while(true) {
System.err.print(".");
socket.send(dgram);
Thread.sleep(1000);
}
40. ADVANCE JAVA
Classified e-Material 40
Multicast Example
byte[] b = new byte[BUFFER_LENGTH];
DatagramPacket dgram = new DatagramPacket(b,
b.length);
MulticastSocket socket = new
MulticastSocket(DEST_PORT); // must bind receive side
socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
while(true) {
socket.receive(dgram); // blocks until a datagram is
received System.err.println("Received " +
dgram.getLength() + " bytes from " +
dgram.getAddress());
dgram.setLength(b.length); // must reset length field!
}
41. ADVANCE JAVA
Classified e-Material 41
URL Class
Represents a Uniform Resource Locator, a pointer
to a "resource" on the World Wide Web.
Consist of a protocol, host name, path and file
name.
Example:
http://archive.ncsa.uiuc.edu/SDG/Software/Mosaic/Demo/
It may contains either relative or absolute path of
file.
42. ADVANCE JAVA
Classified e-Material 42
URL Class - Constructors
URL(String spec)
Creates a URL object from the String representation
URL(String protocol, String host, int port, String file)
Creates a URL object from the specified protocol, host,
port number, and file
URL(String protocol, String host, int port, String file,
URLStreamHandler handler)
Creates a URL object from the specified protocol, host,
port number, file, and handler.
43. ADVANCE JAVA
Classified e-Material 43
URL(String protocol, String host, String file)
Creates a URL from the specified protocol name, host
name, and file name
URL(URL context, String spec)
Creates a URL by parsing the given spec within a
specified context
URL(URL context, String spec,
URLStreamHandler handler)
Creates a URL by parsing the given spec with the
specified handler within a specified context.
44. ADVANCE JAVA
Classified e-Material 44
URL Class - Methods
Object getContent()
Gets the contents of this URL.
Int getDefaultPort()
Gets the default port number of the protocol
associated with this URL.
String getFile()
Gets the file name of this URL
String getHost()
Gets the host name of this URL, if applicable.
String getPath()
Gets the path part of this URL.
45. ADVANCE JAVA
Classified e-Material 45
URL Class - Methods
int getPort()
Gets the port number of this URL.
String getProtocol()
Gets the protocol name of this URL.
String getQuery()
Gets the query part of this URL
InputStream openStream()
Opens a connection to this URL and returns an
InputStream for reading from that connection.
protected void set(String protocol, String host,
int port, String file, String ref)
Sets the fields of the URL.
protected void set(String protocol, String host,
int port, String authority, String userInfo, String path,
String query, String ref)
Sets the specified 8 fields of the URL.
46. ADVANCE JAVA
Classified e-Material 46
URL Class - example
import java.lang.System;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
public class GetURLApp {
public static void main(String args[]){
try{ if(args.length!=1) error("Usage: java GetURLApp
URL");
System.out.println("Fetching URL: "+args[0]);
URL url = new URL(args[0]);
BufferedReader inStream = new BufferedReader( new
InputStreamReader(url.openStream()));
48. ADVANCE JAVA
Classified e-Material 48
URLConnection and HTTPURLConnection class
URLConnection
It is an abstract class.
It gives information about the web object,
connection to web object.
It provides the way to interact with the web object.
Example
URL url = new URL ("http://www.google.com/");
InputStream inputStream = url.openStream ();
OR
URL url = new URL ("http://www.google.com/");
URLConnection urlConnection = url.openConnection
();
InputStream inputStream = urlConnection.getInput
Stream ();
49. ADVANCE JAVA
Classified e-Material 49
URLConnection
The URL is constructed.
The URL’s openConnection() method creates the
URLConnection object.
The parameters for the connection and the
request properties that the client sends to the
server are set up.
The connect() method makes the connection to
the server. (optional)
The response header information is read using
getHeaderField().
50. ADVANCE JAVA
Classified e-Material 50
Header Viewer Example
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class MainClass {
public static void main(String args[]) throws Excep
tion {
URL u = new URL("http://www.java2s.com");
URLConnection uc = u.openConnection();
System.out.println("Content-
type: " + uc.getContentType());
System.out.println("Content-
encoding: " + uc.getContentEncoding());
System.out.println("Date: " + new Date(uc.getD
ate()));
51. ADVANCE JAVA
Classified e-Material 51
System.out.println("Last modified: " + new Date(uc.g
etLastModified()));
System.out.println("Expiration date: " + new Date(
uc.getExpiration()));
System.out.println("Content-
length: " + uc.getContentLength());
}}
Output:
Content-type: text/html
Content-encoding: null
Date: Thu May 24 18:41:00 PDT 2007
Last modified: Fri May 18 08:20:08 PDT 2007
Expiration date: Wed Dec 31 16:00:00 PST 1969
Content-length: 345648
52. ADVANCE JAVA
Classified e-Material 52
Writing to a Web server
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
public static void main(String[] a)throws Exception
{
URL url = new URL("http://www.yourdomain.com
/form.jsp");
URLConnection connection = url.openConnection()
;
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getO
utputStream());
out.println("firstName=Joe");
out.println("lastName=Average");
out.close();
}
}
56. ADVANCE JAVA
Classified e-Material 56
MIME
MIME is an acronym for "Multipurpose Internet
Mail Extensions".
An Internet standard defined in RFCs 2045
through 2049
Originally intended for use with email messages,
but has been been adopted for use in HTTP.
57. ADVANCE JAVA
Classified e-Material 57
Browser Request MIME Header
When the browser sends a request to a web
server, it also sends a MIME header.
MIME headers contain name-value pairs,
essentially a name followed by a colon and a
space, followed by a value.
Connection: Keep-Alive
User-Agent: Mozilla/3.01 (Macintosh; I; PPC)
Host: www.digitalthink.com:80
Accept: image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg, */*
58. ADVANCE JAVA
Classified e-Material 58
Server Response MIME Header
When a web server responds to a web browser it
sends a response message and a MIME header
along with the response that looks something like
this:
HTTP/1.0 200 OK
Server: Netscape-Enterprise/2.01
Date: Sat, 02 Aug 1997 07:52:46 GMT
Accept-ranges: bytes
Last-modified: Tue, 29 Jul 1997 15:06:46 GMT
Content-length: 2810
Content-type: text/html