SlideShare a Scribd company logo
Socket Programming in Java
-First Step of Network Programming-
2
Network
R
e
q
u
e
s
t
Result
a client, a server, and network
Client
Server
Client machine
Server machine
Elements of C-S Computing
3
Networking Basics
• Applications Layer
– Standard apps
• HTTP
• FTP
• Telnet
– User apps
• Transport Layer
– TCP
– UDP
– Programming Interface:
• Sockets
• Network Layer
– IP
• Link Layer
– Device drivers
• TCP/IP Stack
Application
(http,ftp,telnet,…)
Transport
(TCP, UDP,..)
Network
(IP,..)
Link
(device driver,..)
4
Networking Basics
• TCP (Transport Control
Protocol) is a connection-
oriented protocol that
provides a reliable flow of
data between two
computers.
• Example applications:
– HTTP
– FTP
– Telnet
• TCP/IP Stack
Application
(http,ftp,telnet,…)
Transport
(TCP, UDP,..)
Network
(IP,..)
Link
(device driver,..)
5
Networking Basics
• UDP (User Datagram
Protocol) is a protocol that
sends independent packets
of data, called datagrams,
from one computer to
another with no guarantees
about arrival.
• Example applications:
– Ping
• TCP/IP Stack
Application
(http,ftp,telnet,…)
Transport
(TCP, UDP,..)
Network
(IP,..)
Link
(device driver,..)
6
Understanding Ports
• The TCP and UDP
protocols use ports to
map incoming data to a
particular process
running on a computer.
server
P
o
r
t
Client
TCP
TCP or UDP
port port port port
app app app app
port# data
Data
Packet
7
Understanding Ports
• Port is represented by a positive (16-bit) integer
value
• Some ports have been reserved to support
common/well known services:
– ftp 21/tcp
– telnet 23/tcp
– smtp 25/tcp
– login 513/tcp
• User level process/services generally use port
number value >= 1024
8
Socket Communication
• A server (program) runs on a specific
computer and has a socket that is bound to a
specific port. The server waits and listens to
the socket for a client to make a connection
request.
server
Client
Connection request
port
9
Socket Communication
• If everything goes well, the server accepts the connection.
Upon acceptance, the server gets a new socket bounds to a
different port. It needs a new socket (consequently a different
port number) so that it can continue to listen to the original
socket for connection requests while serving the connected
client.
server
Client
Connection
port
port
port
10
Sockets and Java Socket Classes
• A socket is an endpoint of a two-way
communication link between two programs
running on the network.
• A socket is bound to a port number so that the
TCP layer can identify the application that
data destined to be sent.
• Java’s .net package provides two classes:
– Socket – for implementing a client
– ServerSocket – for implementing a server
11
Java Sockets
ServerSocket(1234)
Socket(“128.250.25.158”, 1234)
Output/write stream
Input/read stream
It can be host_name like “iiu.edu.pk”
Client
Server
12
Server
Threads
Server Process
Client 1 Process
Client 2 Process
Multithreaded Server: For Serving
Multiple Clients Concurrently
Internet
How to Open a Socket?
-Client-
Socket MyClient;
MyClient = new Socket("Machine name",
PortNumber);
How to Open a Socket?
-Client-
• With exception handling, the code look like
following:
Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
How to Open a Socket?
-Server-
ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
How Do I Create an Input Stream?
-Client-
• On the client side, you can use the DataInputStream class to
create an input stream to receive response from the server:
DataInputStream input;
try {
input = new DataInputStream(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
How Do I Create an Input Stream?
-Client-
• The class DataInputStream allows you to read
lines of text and Java primitive data types in a
portable way.
• It has methods such as read, readChar,
readInt, readDouble, and readLine,.
• Use whichever function you think suits your
needs depending on the type of data that you
receive from the server.
How Do I Create an Input Stream?
-Server-
• On the server side, you can use DataInputStream to receive
input from the client
DataInputStream input;
try {
input = new DataInputStream(serviceSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
How do I Create an Output Stream?
-Client-
• On the client side, you can create an output
stream to send information to the server
socket using the class PrintStream or
DataOutputStream of java.io:
How do I Create an Output Stream?
-Client-
PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream()); }
catch (IOException e) {
System.out.println(e);
}
How do I Create an Output Stream?
-Client-
• The class PrintStream has methods for
displaying textual representation of Java
primitive data types.
• you may use the DataOutputStream
How do I Create an Output Stream?
-Client-
DataOutputStream output;
try {
output = new DataOutputStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
How do I Create an Output Stream?
-Client-
• The class DataOutputStream allows you to
write Java primitive data types; many of its
methods write a single Java primitive type to
the output stream.
• The method writeBytes is a useful one.
How do I Create an Output Stream?
-Server-
• On the server side, you can use the class PrintStream to send
information to the client.
PrintStream output;
try {
output = new
PrintStream(serviceSocket.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
How do I Create an Output Stream?
-Server-
• You can use the class DataOutputStream as
mentioned
DataOutputStream output;
try {
output = new
DataOutputStream(serviceSocket.getOutputStream()
);
}
catch (IOException e) {
System.out.println(e);
}
How Do I Close Sockets?
-Client-
• You should always close the output and input stream
before you close the socket.
try {
output.close();
input.close();
MyClient.close();
}
catch (IOException e) {
System.out.println(e);
}
How Do I Close Sockets?
-Server-
try {
output.close();
input.close();
serviceSocket.close();
MyService.close();
}
catch (IOException e) {
System.out.println(e);
}
28
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();
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.
}
29
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();
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)
Sockets
: Client socket, welcoming socket and connection socket
Socket-programming using TCP
TCP service: reliable byte stream transfer
process
TCP with
buffers,
variables
socket
controlled by
application
developer
controlled by
operating
system
process
TCP with
buffers,
variables
socket
internet
client
server
socket( )
bind( )
connect( )
socket( )
bind( )
listen( )
accept( )
send( )
recv( )
close( ) close( )
recv( )
send( )
TCP conn. request
TCP ACK
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)
outT
oServer
to network from network
inFromServer
inFromUser
keyboard monitor
Process
clientSocket
input
stream
input
stream
output
stream
TCP
socket
Input stream:
sequence of bytes
into process
output stream:
sequence of bytes
out of process
Client
process
client TCP
socket
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
clientSocket
read request from
connectionSocket
write reply to
connectionSocket
TCP
connection setup
35
Example: Java client (TCP)
import java.io.*;
import java.net.*;
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());
Create
input stream
Create
client socket,
connect to server
Create
output stream
attached to socket
36
Example: Java client (TCP), cont.
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();
}
}
Create
input stream
attached to socket
Send line
to server
Read line
from server
37
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
Create
welcoming socket
at port 6789
Wait, on welcoming
socket for contact
by client
Create input
stream, attached
to socket
38
Example: Java server (TCP), cont
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Read in line
from socket
Create output
stream, attached
to socket
Write out line
to socket
End of while loop,
loop back and wait for
another client connection
39
Socket programming with UDP
UDP: no “connection” between
client and server
• no handshaking
• sender explicitly attaches IP
address and port of destination
to each packet
• server must extract IP address,
port of sender from received
packet
UDP: transmitted data may be
received out of order, or lost
application viewpoint
UDP provides unreliable transfer
of groups of bytes (“datagrams”)
between client and server
40
Example: Java client (UDP)
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
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();
Create
input stream
Create
client socket
Translate
hostname to IP
address using DNS
41
Example: Java client (UDP), cont.
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
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();
}
}
Create datagram with
data-to-send,
length, IP addr, port
Send datagram
to server
Read datagram
from server
42
Example: Java server (UDP)
import java.io.*;
import java.net.*;
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, receiveData.length);
serverSocket.receive(receivePacket);
Create
datagram socket
at port 9876
Create space for
received datagram
Receive
datagram
43
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
}
Get IP addr
port #, of
sender
Write out
datagram
to socket
End of while loop,
loop back and wait for
another datagram
Create datagram
to send to client

More Related Content

PPT
Sockets
sivindia
 
PPT
Network programming in Java
Tushar B Kute
 
PPT
Network Programming in Java
Tushar B Kute
 
PDF
JavaSockets-Session10 New York university.pdf
jose19881
 
PPT
java networking
Waheed Warraich
 
PPT
Network programming in Java
Tushar B Kute
 
PDF
28 networking
Ravindra Rathore
 
PPTX
Java 1
VidyaVarshini3
 
Sockets
sivindia
 
Network programming in Java
Tushar B Kute
 
Network Programming in Java
Tushar B Kute
 
JavaSockets-Session10 New York university.pdf
jose19881
 
java networking
Waheed Warraich
 
Network programming in Java
Tushar B Kute
 
28 networking
Ravindra Rathore
 

Similar to Socket Programming in Java.ppt yeh haii (20)

PPTX
Chapter 4--converted.pptx
WijdenBenothmen1
 
PPTX
A.java
JahnaviBhagat
 
PPT
Socket Programming - nitish nagar
Nitish Nagar
 
PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
PPTX
5_6278455688045789623.pptx
EliasPetros
 
PPT
Unit 8 Java
arnold 7490
 
PPTX
Networking in Java
Tushar B Kute
 
PDF
Network Programming Clients
Adil Jafri
 
PDF
15network Programming Clients
Adil Jafri
 
DOC
T2
Mo Ch
 
PPTX
Networking.pptx
Esubesisay
 
PPT
Networking Java Socket Programming
Mousmi Pawar
 
PPT
Socket programming-tutorial-sk
sureshkarthick37
 
PPTX
Basics of Socket Programming using python
NalinadeviKadiresan1
 
PPTX
Networking in Python2025 (programs allll)
PriyankaPatil919748
 
PPT
Lan chat system
Wipro
 
PDF
Lecture set 7
Gopi Saiteja
 
PPTX
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
PPT
Java Networking
Sunil OS
 
Chapter 4--converted.pptx
WijdenBenothmen1
 
Socket Programming - nitish nagar
Nitish Nagar
 
Java socket programming
Mohammed Abdalla Youssif
 
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
5_6278455688045789623.pptx
EliasPetros
 
Unit 8 Java
arnold 7490
 
Networking in Java
Tushar B Kute
 
Network Programming Clients
Adil Jafri
 
15network Programming Clients
Adil Jafri
 
T2
Mo Ch
 
Networking.pptx
Esubesisay
 
Networking Java Socket Programming
Mousmi Pawar
 
Socket programming-tutorial-sk
sureshkarthick37
 
Basics of Socket Programming using python
NalinadeviKadiresan1
 
Networking in Python2025 (programs allll)
PriyankaPatil919748
 
Lan chat system
Wipro
 
Lecture set 7
Gopi Saiteja
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
Java Networking
Sunil OS
 
Ad

Recently uploaded (20)

PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PDF
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PDF
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
Understanding operators in c language.pptx
auteharshil95
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Ad

Socket Programming in Java.ppt yeh haii

  • 1. Socket Programming in Java -First Step of Network Programming-
  • 2. 2 Network R e q u e s t Result a client, a server, and network Client Server Client machine Server machine Elements of C-S Computing
  • 3. 3 Networking Basics • Applications Layer – Standard apps • HTTP • FTP • Telnet – User apps • Transport Layer – TCP – UDP – Programming Interface: • Sockets • Network Layer – IP • Link Layer – Device drivers • TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
  • 4. 4 Networking Basics • TCP (Transport Control Protocol) is a connection- oriented protocol that provides a reliable flow of data between two computers. • Example applications: – HTTP – FTP – Telnet • TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
  • 5. 5 Networking Basics • UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. • Example applications: – Ping • TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
  • 6. 6 Understanding Ports • The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. server P o r t Client TCP TCP or UDP port port port port app app app app port# data Data Packet
  • 7. 7 Understanding Ports • Port is represented by a positive (16-bit) integer value • Some ports have been reserved to support common/well known services: – ftp 21/tcp – telnet 23/tcp – smtp 25/tcp – login 513/tcp • User level process/services generally use port number value >= 1024
  • 8. 8 Socket Communication • A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request. server Client Connection request port
  • 9. 9 Socket Communication • If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. server Client Connection port port port
  • 10. 10 Sockets and Java Socket Classes • A socket is an endpoint of a two-way communication link between two programs running on the network. • A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent. • Java’s .net package provides two classes: – Socket – for implementing a client – ServerSocket – for implementing a server
  • 11. 11 Java Sockets ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream It can be host_name like “iiu.edu.pk” Client Server
  • 12. 12 Server Threads Server Process Client 1 Process Client 2 Process Multithreaded Server: For Serving Multiple Clients Concurrently Internet
  • 13. How to Open a Socket? -Client- Socket MyClient; MyClient = new Socket("Machine name", PortNumber);
  • 14. How to Open a Socket? -Client- • With exception handling, the code look like following: Socket MyClient; try { MyClient = new Socket("Machine name", PortNumber); } catch (IOException e) { System.out.println(e); }
  • 15. How to Open a Socket? -Server- ServerSocket MyService; try { MyServerice = new ServerSocket(PortNumber); } catch (IOException e) { System.out.println(e); }
  • 16. How Do I Create an Input Stream? -Client- • On the client side, you can use the DataInputStream class to create an input stream to receive response from the server: DataInputStream input; try { input = new DataInputStream(MyClient.getInputStream()); } catch (IOException e) { System.out.println(e); }
  • 17. How Do I Create an Input Stream? -Client- • The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. • It has methods such as read, readChar, readInt, readDouble, and readLine,. • Use whichever function you think suits your needs depending on the type of data that you receive from the server.
  • 18. How Do I Create an Input Stream? -Server- • On the server side, you can use DataInputStream to receive input from the client DataInputStream input; try { input = new DataInputStream(serviceSocket.getInputStream()); } catch (IOException e) { System.out.println(e); }
  • 19. How do I Create an Output Stream? -Client- • On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io:
  • 20. How do I Create an Output Stream? -Client- PrintStream output; try { output = new PrintStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }
  • 21. How do I Create an Output Stream? -Client- • The class PrintStream has methods for displaying textual representation of Java primitive data types. • you may use the DataOutputStream
  • 22. How do I Create an Output Stream? -Client- DataOutputStream output; try { output = new DataOutputStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); }
  • 23. How do I Create an Output Stream? -Client- • The class DataOutputStream allows you to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. • The method writeBytes is a useful one.
  • 24. How do I Create an Output Stream? -Server- • On the server side, you can use the class PrintStream to send information to the client. PrintStream output; try { output = new PrintStream(serviceSocket.getOutputStream()); } catch (IOException e) { System.out.println(e); }
  • 25. How do I Create an Output Stream? -Server- • You can use the class DataOutputStream as mentioned DataOutputStream output; try { output = new DataOutputStream(serviceSocket.getOutputStream() ); } catch (IOException e) { System.out.println(e); }
  • 26. How Do I Close Sockets? -Client- • You should always close the output and input stream before you close the socket. try { output.close(); input.close(); MyClient.close(); } catch (IOException e) { System.out.println(e); }
  • 27. How Do I Close Sockets? -Server- try { output.close(); input.close(); serviceSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); }
  • 28. 28 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(); 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. }
  • 29. 29 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();
  • 30. 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)
  • 31. Sockets : Client socket, welcoming socket and connection socket
  • 32. Socket-programming using TCP TCP service: reliable byte stream transfer process TCP with buffers, variables socket controlled by application developer controlled by operating system process TCP with buffers, variables socket internet client server socket( ) bind( ) connect( ) socket( ) bind( ) listen( ) accept( ) send( ) recv( ) close( ) close( ) recv( ) send( ) TCP conn. request TCP ACK
  • 33. 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) outT oServer to network from network inFromServer inFromUser keyboard monitor Process clientSocket input stream input stream output stream TCP socket Input stream: sequence of bytes into process output stream: sequence of bytes out of process Client process client TCP socket
  • 34. 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 clientSocket read request from connectionSocket write reply to connectionSocket TCP connection setup
  • 35. 35 Example: Java client (TCP) import java.io.*; import java.net.*; 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()); Create input stream Create client socket, connect to server Create output stream attached to socket
  • 36. 36 Example: Java client (TCP), cont. 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(); } } Create input stream attached to socket Send line to server Read line from server
  • 37. 37 Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket
  • 38. 38 Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence); } } } Read in line from socket Create output stream, attached to socket Write out line to socket End of while loop, loop back and wait for another client connection
  • 39. 39 Socket programming with UDP UDP: no “connection” between client and server • no handshaking • sender explicitly attaches IP address and port of destination to each packet • server must extract IP address, port of sender from received packet UDP: transmitted data may be received out of order, or lost application viewpoint UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server
  • 40. 40 Example: Java client (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 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(); Create input stream Create client socket Translate hostname to IP address using DNS
  • 41. 41 Example: Java client (UDP), cont. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); 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(); } } Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server
  • 42. 42 Example: Java server (UDP) import java.io.*; import java.net.*; 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, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 Create space for received datagram Receive datagram
  • 43. 43 Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Get IP addr port #, of sender Write out datagram to socket End of while loop, loop back and wait for another datagram Create datagram to send to client