SlideShare a Scribd company logo
1 of 45
Java Socket Programming
Java Sockets Programming
 The package java.net provides support for
sockets programming (and more).
 Typically you import everything defined in
this package with:
import java.net.*;
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 = InetAddress.getByName(
“cse.unr.edu”);
 Throws UnknownHostException
Java Socket Programming 4
try {
InetAddress a = InetAddress.getByName(hostname);
System.out.println(hostname + ":" + a.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("No address found for " + hostname);
}
try {
InetAddress a = InetAddress.getByName(hostname);
System.out.println(hostname + ":" + a.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("No address found for " + 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 6
JAVA TCP Sockets (Client
Socket)
 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()
Java Socket Programming 7
ServerSocket
 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.
Internet 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 java.io
 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 b.length 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
Example client-server app:
 client reads line from standard
input (inFromUser stream) ,
sends to server via socket
(outToServer stream)
 server reads line from socket
 server converts line to
uppercase, sends back to client
 client reads, prints modified
line from socket
(inFromServer stream)
outToServer
tonetwork fromnetwork
inFromServer
inFromUser
keyboard monitor
Process
clientSocket
input
stream
input
stream
output
stream
TCP
socket
Input stream:
sequence of bytes
into processoutput stream:
sequence of bytes
out of process
Client
process
client TCP
socket
Java Socket Programming 17
Client/server socket interaction: TCP
wait for incoming
connection request
connectionSocket =
welcomeSocket.accept()
create socket,
port=x,
for incoming request:
welcomeSocket =
ServerSocket()
create socket,
connect to hostid, port=x
clientSocket = Socket()
close
connectionSocket
read reply from
clientSocket
close
clientSocket
Server (running on hostid) Client
send request using
clientSocketread request from
connectionSocket
write reply to
connectionSocket
TCP
connection setup
Java Socket Programming 18
Sample Echo Server
TCPEchoServer.java
And TCPClient.java
Save both files, compile and run on separate terminal.
First TCPEchoServer and then TCPClient
Based on code from:
TCP/IP Sockets in Java
Java Socket Programming 19
TCPEchoServer.java
import java.io.*;
import java.net.*;
Public class TCPEchoServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
// server running and listening
while(true) {
Socket connectionSocket = welcomeSocket.accept();
// new client connected
BufferedReader inFromClient = new BufferedReader
(new InputStreamReader
(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream
(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase()+ ‘n’;
outToClient.writeBytes(capitalizedSentence);
}
}
}
Java Socket Programming 21
TCPClient.java
import java.io.*;
import java.net.*;
Public class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer = new DataOutputStream
(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
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.
 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 java.net
 java.net.DatagramSocket
• 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
DatagramPacket
 Contain the payload
 (a byte array, length of byte array,
InetAddress, port)
 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)
sendPacket
tonetwork fromnetwork
receivePacket
inFromUser
keyboard monitor
Process
clientSocket
UDP
packet
input
stream
UDP
packet
UDP
socket
Output: sends
packet (TCP sent
“byte stream”)
Input: receives
packet (TCP
received “byte
stream”)
Client
process
client UDP
socket
Java Socket Programming 32
Client/server socket interaction: UDP
close
clientSocket
Server (running on hostid)
read reply from
clientSocket
create socket,
clientSocket = DatagramSocket()
Client
Create, address (hostid, port=x,
send datagram request
using clientSocket
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port umber
Java Socket Programming 33
Sample UDP code
UDPEchoServer.java
Simple UDP Echo server.
Test using nc as the client (netcat):
> nc –u hostname port
Java Socket Programming 34
UDPEchoServer.java
import java.io.*;
import java.net.*;
class UDPEchoServer {
public static void main(String args[]) throws Exception {
int port = 9876;
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true) {
DatagramPacket receivePacket =
new DatagramPacket (receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket
(sendData, sendData.length, IPAddress, clientPort);
serverSocket.send(sendPacket);
}
}
}
Java Socket Programming 36
UDPClient.java
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser = new BufferedReader
(new InputStreamReader (System.in));
int port = 9876;
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket (sendData,
sendData.length, IPAddress, port);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket
(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
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(“http://www.cs.unr.edu/”);
System.out.println(“Proto:” + u.getProtocol());
System.out.println(“File:” + u.getFile());
Java Socket Programming 41
URL construction
 You can also build a URL by setting each part individually:
URL u = new URL(“http”,
www.cs.unr.edu,80,”/~mgunes/”);
System.out.println(“URL:” + u.toExternalForm());
System.out.println(“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 (“file://c:foo.html”)
 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

More Related Content

What's hot

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 

What's hot (20)

Applets in java
Applets in javaApplets in java
Applets in java
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java IO
Java IOJava IO
Java IO
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Files in java
Files in javaFiles in java
Files in java
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 

Similar to Java Socket Programming

TCP IP
TCP IPTCP IP
TCP IP
hivasu
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
hendriciraida
 
I need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docxI need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docx
hendriciraida
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
yayaria
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0s
naniix21_3
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
jobandesther
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 

Similar to Java Socket Programming (20)

Networking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programNetworking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in program
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Lecture6
Lecture6Lecture6
Lecture6
 
Network programming1
Network programming1Network programming1
Network programming1
 
TCP IP
TCP IPTCP IP
TCP IP
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 
Java 1
Java 1Java 1
Java 1
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
 
java sockets
 java sockets java sockets
java sockets
 
Ipc
IpcIpc
Ipc
 
I need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docxI need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docx
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0s
 
Network
NetworkNetwork
Network
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

Java Socket Programming

  • 2. Java Sockets Programming  The package java.net provides support for sockets programming (and more).  Typically you import everything defined in this package with: import java.net.*; Java Socket Programming 2
  • 4. InetAddress class  static methods you can use to create new InetAddress objects.  getByName(String host)  getAllByName(String host)  getLocalHost() InetAddress x = InetAddress.getByName( “cse.unr.edu”);  Throws UnknownHostException Java Socket Programming 4
  • 5. try { InetAddress a = InetAddress.getByName(hostname); System.out.println(hostname + ":" + a.getHostAddress()); } catch (UnknownHostException e) { System.out.println("No address found for " + hostname); } try { InetAddress a = InetAddress.getByName(hostname); System.out.println(hostname + ":" + a.getHostAddress()); } catch (UnknownHostException e) { System.out.println("No address found for " + hostname); } Java Socket Programming
  • 6. 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 6
  • 7. JAVA TCP Sockets (Client Socket)  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() Java Socket Programming 7
  • 8. ServerSocket  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. Internet 8
  • 9. Sockets Client socket, welcoming socket (passive) and connection socket (active) Java Socket Programming 9
  • 10. 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
  • 11. 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
  • 12. Socket I/O  Socket I/O is based on the Java I/O support  in the package java.io  InputStream and OutputStream are abstract classes  common operations defined for all kinds of InputStreams, OutputStreams… Java Socket Programming 12
  • 13. 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
  • 14. OutputStream Basics // writes b.length 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
  • 15. 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
  • 16. ServerSocket Methods Socket accept(); void close(); InetAddress getInetAddress(); int getLocalPort(); throw IOException, SecurityException Java Socket Programming 16
  • 17. Socket programming with TCP Example client-server app:  client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream)  server reads line from socket  server converts line to uppercase, sends back to client  client reads, prints modified line from socket (inFromServer stream) outToServer tonetwork fromnetwork inFromServer inFromUser keyboard monitor Process clientSocket input stream input stream output stream TCP socket Input stream: sequence of bytes into processoutput stream: sequence of bytes out of process Client process client TCP socket Java Socket Programming 17
  • 18. Client/server socket interaction: TCP wait for incoming connection request connectionSocket = welcomeSocket.accept() create socket, port=x, for incoming request: welcomeSocket = ServerSocket() create socket, connect to hostid, port=x clientSocket = Socket() close connectionSocket read reply from clientSocket close clientSocket Server (running on hostid) Client send request using clientSocketread request from connectionSocket write reply to connectionSocket TCP connection setup Java Socket Programming 18
  • 19. Sample Echo Server TCPEchoServer.java And TCPClient.java Save both files, compile and run on separate terminal. First TCPEchoServer and then TCPClient Based on code from: TCP/IP Sockets in Java Java Socket Programming 19
  • 20. TCPEchoServer.java import java.io.*; import java.net.*; Public class TCPEchoServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); // server running and listening while(true) { Socket connectionSocket = welcomeSocket.accept(); // new client connected BufferedReader inFromClient = new BufferedReader (new InputStreamReader (connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
  • 21. clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase()+ ‘n’; outToClient.writeBytes(capitalizedSentence); } } } Java Socket Programming 21
  • 22. TCPClient.java import java.io.*; import java.net.*; Public class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream (clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  • 23. sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + 'n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Java Socket Programming 23
  • 24. UDP Sockets  DatagramSocket class  DatagramPacket class needed to specify the payload  incoming or outgoing Java Socket Programming 24
  • 25. Socket Programming with UDP  UDP  Connectionless and unreliable service.  There isn’t an initial handshaking phase.  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
  • 26. JAVA UDP Sockets  In Package java.net  java.net.DatagramSocket • 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
  • 27. DatagramSocket Constructors DatagramSocket(); DatagramSocket(int port); DatagramSocket(int port, InetAddress a); All can throw SocketException or SecurityException Java Socket Programming 27
  • 28. Datagram Methods void connect(InetAddress, int port); void close(); void receive(DatagramPacket p); void send(DatagramPacket p); Lots more! Java Socket Programming 28
  • 29. DatagramPacket  Contain the payload  (a byte array, length of byte array, InetAddress, port)  Can also be used to specify the destination address  when not using connected mode UDP Java Socket Programming 29
  • 30. DatagramPacket Constructors For receiving: DatagramPacket( byte[] buf, int len); For sending: DatagramPacket( byte[] buf, int len InetAddress a, int port); Java Socket Programming 30
  • 31. DatagramPacket methods byte[] getData(); void setData(byte[] buf); void setAddress(InetAddress a); void setPort(int port); InetAddress getAddress(); int getPort(); Java Socket Programming 31
  • 32. Example: Java client (UDP) sendPacket tonetwork fromnetwork receivePacket inFromUser keyboard monitor Process clientSocket UDP packet input stream UDP packet UDP socket Output: sends packet (TCP sent “byte stream”) Input: receives packet (TCP received “byte stream”) Client process client UDP socket Java Socket Programming 32
  • 33. Client/server socket interaction: UDP close clientSocket Server (running on hostid) read reply from clientSocket create socket, clientSocket = DatagramSocket() Client Create, address (hostid, port=x, send datagram request using clientSocket create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client host address, port umber Java Socket Programming 33
  • 34. Sample UDP code UDPEchoServer.java Simple UDP Echo server. Test using nc as the client (netcat): > nc –u hostname port Java Socket Programming 34
  • 35. UDPEchoServer.java import java.io.*; import java.net.*; class UDPEchoServer { public static void main(String args[]) throws Exception { int port = 9876; DatagramSocket serverSocket = new DatagramSocket(port); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress();
  • 36. int clientPort = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, clientPort); serverSocket.send(sendPacket); } } } Java Socket Programming 36
  • 37. UDPClient.java import java.io.*; import java.net.*; public class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader (new InputStreamReader (System.in)); int port = 9876; DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();
  • 38. DatagramPacket sendPacket = new DatagramPacket (sendData, sendData.length, IPAddress, port); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket (receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Java Socket Programming 38
  • 39. 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
  • 40. Java URL Class  Represents a Uniform Resource Locator  scheme (protocol)  hostname  port  path  query string Java Socket Programming 40
  • 41. Parsing  You can use a URL object as a parser: URL u = new URL(“http://www.cs.unr.edu/”); System.out.println(“Proto:” + u.getProtocol()); System.out.println(“File:” + u.getFile()); Java Socket Programming 41
  • 42. URL construction  You can also build a URL by setting each part individually: URL u = new URL(“http”, www.cs.unr.edu,80,”/~mgunes/”); System.out.println(“URL:” + u.toExternalForm()); System.out.println(“URL: “ + u); Java Socket Programming 42
  • 43. 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 (“file://c:foo.html”)  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
  • 44. Getting Header Information  There are methods that return information extracted from response headers: String getContentType(); String getContentLength(); long getLastModified(); Java Socket Programming 44
  • 45. 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