SlideShare a Scribd company logo
1 of 20
Download to read offline
Networking with Java
CSc 335
Object-Oriented Programming and Design
Craig Barber, Ian Vasquez, Rick Snodgrass, Rick Mercer
Networking
Refactoring Y-2
Refactoring Y-2
Refactoring Y-2
Concurrency
Networks
Serialization
Javadoc
JUnit
Eclipse
Debugging
Testing &
Maintaing
Large
Programs
Teams
Reading
others’
code
MVC
Observer
Observable
Design
Patterns
UML
Class
Diagrams
Inheritance
Hierarchy
Coupling/
Cohesion
OO Design
PITL
Sequence
Diagrams
Package
Diagrams
Anonymous
Classes
Abstract
Classes
Packages
JDK/JRE
Java Language
Compile-Time
Run-Time
Type Resolution
Type Checking
Java Swing
Frameworks
Java API
Inversion
of Control
Layout
Manager
Listeners
Events
I/O
Iterator
Collection
Exceptions
Composite
Command
Template
Decorator
N-2
Networking with Java N-3
Outline
• Introduction to Networking Concepts
 Client-Server and Peer-to-Peer
 Sockets
 Streams
Networking with Java N-4
What is “Networking”
• What is “Networking”?
 Getting two or more computers to send data (in Java--
serialized objects) to each other
 Having programs on separate computers interact with one
another
• Types of Networking
 Client - Server
 Many clients connect with one server.
 Clients communicate only with server.
 Peer-to-Peer
 Clients connect to a group of other clients, with no server.
 Clients communicating directly with each-other.
Networking with Java N-5
Client - Server Networking
• Advantages:
 Easier to implement
 Less coordination
involved
 Easier to maintain
control of users
• Disadvantage:
 Relies on one main
server for entire
operation
Networking with Java N-6
How Can Networking Work?
• Computers connect to each other through links called
sockets, each associated with a single computer.
• A network stream is created by connecting a socket on
one computer to a socket on another computer
• Applications communicate by sending data through
streams to each other
 Reading and writing objects over the network employs the
same serialization you used for persistence
Networking with Java N-7
Sockets
• A socket is a connection on one computer used to send
data back and forth
• The application consists of multiple processes, one
running on each computer
• Sockets are created by the process on each computer
• The sockets then establish a connection to each other
 One process sets up a server socket to receive a connection.
 The other process sets up a client socket to establish the
connection with the server socket.
Networking with Java N-8
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
Networking with Java N-9
Outline
• Introduction to Networking Concepts
• Networking in Java
 Sockets
 Streams
 Decorating Streams
• Summary
Networking with Java N-10
Sockets in Java
• Found in java.net package
• java.net.ServerSocket
 Accepts new incoming connections
 Creates new ServerSocket for each connection
• java.net.Socket
 Connects to an existing ServerSocket, through the
network
Sockets in Java
Networking with Java N-11
Host Machine
Process
Client Machine
Process
Server
Socket
Input
Socket
Output
Socket
Socket
Socket
Socket
Input
Socket
Process
Socket
Client Machine
Two new types
Networking with Java N-12
• We'll be using two new types
• java.net.ServerSocket
• java.net.Socket
 You can write to and read from a Socket's input and
output streams with readObject and writeObject messages
 which makes networked programs easier to develop
Networking with Java N-13
java.net.ServerSocket
• public ServerSocket(int port)
 Throws IOException
 Creates a ServerSocket to accept new connections at the specified
port
• public Socket accept()
 Throws IOException
 Waits for an incoming connection, establishes the new connection, and
returns a socket for that connection
 Multiple applications can connect to the same ServerSocket
• public void close()
 Throws IOException
 Closes the server socket.
 Does not close open sockets.
Networking with Java N-14
java.net.Socket
• public Socket(String host, int port)
 Throws IOException, UnknownHostException
 Connects to a server socket at the provided address (host) on the provided
port
• public InputStream getInputStream()
 Throws IOException
 Returns the input stream from the socket
• public OutputStream getOutputStream()
 Throws IOException
 Returns the output stream from the socket
• public void close()
 Throws IOException
 Closes the connection
Networking with Java N-15
Building a Network app
• This app will have one server and only one client (no
Threads needed)
• Build the server first
 Need a new ServerSocket (int port)
 The accept message to ServerSocket waits for a connection
that knows where the server is and what port it is listening to
int port = 4000; // A port available on lectura soince 2003
ServerSocket socket = new ServerSocket(port);
Socket connection = socket.accept();
Networking with Java N-16
Get the connection's streams
• Let the server communicate with the connection
ObjectOutputStream output
= new ObjectOutputStream(connection.getOutputStream());
ObjectInputStream input
= new ObjectInputStream(connection.getInputStream());
Networking with Java N-17
Let the server read and write in loop
• Let the server communicate with the connection
// Take money from the client's account
BankAccount theClientsAccount = null;
BankAccount theServersAccount = new BankAccount("Greedy", 0.00);
while (true) {
double amount = ((Double) input.readObject()).doubleValue();
if (amount <= 0.0)
break;
theClientsAccount = (BankAccount) input.readObject();
if (theClientsAccount.withdraw(amount))
theServersAccount.deposit(amount);
// Send back the modified object
output.writeObject(theClientsAccount);
}
connection.close();
Networking with Java N-18
Write the Client
• Get the input and output stream to and friom the server
we are connecting to
ObjectOutputStream output
= new ObjectOutputStream(server.getOutputStream());
ObjectInputStream input
= new ObjectInputStream(server.getInputStream());
Networking with Java N-19
Write the Client
• Request a socket connection with the running sever
// This IPAddress is for the machine where this code will run
// We'll run the server and the client on the same machine for now
String IPAddress = "localhost"; // There's no place like home
int port = 4000;
Socket server = new Socket(IPAddress, port);
Networking with Java N-20
Let the client read and write in loop
• Let the client communicate with the server
// Give money to the server without knowing it
BankAccount myAccount = new BankAccount("Sucker", 5000.00);
boolean done = false;
while (!done) {
String amountAsString = JOptionPane.showInputDialog(
null,
"You've won! Enter desired amount" + " you have "
+ myAccount.getBalance());
double amount = Double.parseDouble(amountAsString);
output.writeObject(new Double(amount));
if (amount > 0) {
output.writeObject(myAccount);
myAccount = (BankAccount) input.readObject();
} else
// The user figured out how to quit
done = true;
}
server.close();

More Related Content

Similar to 17-Networking.pdf

Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theoryMukesh Tekwani
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using javaUC San Diego
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programmingGera Paulos
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptxRoshniSundrani
 
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 programgovindjha339843
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptssuserec53e73
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptxEsubesisay
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptssuserec53e73
 
Java client socket-20070327
Java client socket-20070327Java client socket-20070327
Java client socket-20070327Tsu-Fen Han
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
04 android
04 android04 android
04 androidguru472
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 

Similar to 17-Networking.pdf (20)

java networking
 java networking java networking
java networking
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theory
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Chapter 4--converted.pptx
Chapter 4--converted.pptxChapter 4--converted.pptx
Chapter 4--converted.pptx
 
Java Network Programming.pptx
Java Network Programming.pptxJava Network Programming.pptx
Java Network Programming.pptx
 
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
 
Client server project
Client server projectClient server project
Client server project
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
A.java
A.javaA.java
A.java
 
Networking.pptx
Networking.pptxNetworking.pptx
Networking.pptx
 
T2
T2T2
T2
 
Java_Socket_Programming (2).ppt
Java_Socket_Programming (2).pptJava_Socket_Programming (2).ppt
Java_Socket_Programming (2).ppt
 
Java client socket-20070327
Java client socket-20070327Java client socket-20070327
Java client socket-20070327
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
04 android
04 android04 android
04 android
 
Socket
SocketSocket
Socket
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
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 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
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.pdfWave PLM
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
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.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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 ...OnePlan Solutions
 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
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 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
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
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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 ...
 

17-Networking.pdf

  • 1. Networking with Java CSc 335 Object-Oriented Programming and Design Craig Barber, Ian Vasquez, Rick Snodgrass, Rick Mercer
  • 2. Networking Refactoring Y-2 Refactoring Y-2 Refactoring Y-2 Concurrency Networks Serialization Javadoc JUnit Eclipse Debugging Testing & Maintaing Large Programs Teams Reading others’ code MVC Observer Observable Design Patterns UML Class Diagrams Inheritance Hierarchy Coupling/ Cohesion OO Design PITL Sequence Diagrams Package Diagrams Anonymous Classes Abstract Classes Packages JDK/JRE Java Language Compile-Time Run-Time Type Resolution Type Checking Java Swing Frameworks Java API Inversion of Control Layout Manager Listeners Events I/O Iterator Collection Exceptions Composite Command Template Decorator N-2
  • 3. Networking with Java N-3 Outline • Introduction to Networking Concepts  Client-Server and Peer-to-Peer  Sockets  Streams
  • 4. Networking with Java N-4 What is “Networking” • What is “Networking”?  Getting two or more computers to send data (in Java-- serialized objects) to each other  Having programs on separate computers interact with one another • Types of Networking  Client - Server  Many clients connect with one server.  Clients communicate only with server.  Peer-to-Peer  Clients connect to a group of other clients, with no server.  Clients communicating directly with each-other.
  • 5. Networking with Java N-5 Client - Server Networking • Advantages:  Easier to implement  Less coordination involved  Easier to maintain control of users • Disadvantage:  Relies on one main server for entire operation
  • 6. Networking with Java N-6 How Can Networking Work? • Computers connect to each other through links called sockets, each associated with a single computer. • A network stream is created by connecting a socket on one computer to a socket on another computer • Applications communicate by sending data through streams to each other  Reading and writing objects over the network employs the same serialization you used for persistence
  • 7. Networking with Java N-7 Sockets • A socket is a connection on one computer used to send data back and forth • The application consists of multiple processes, one running on each computer • Sockets are created by the process on each computer • The sockets then establish a connection to each other  One process sets up a server socket to receive a connection.  The other process sets up a client socket to establish the connection with the server socket.
  • 8. Networking with Java N-8 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
  • 9. Networking with Java N-9 Outline • Introduction to Networking Concepts • Networking in Java  Sockets  Streams  Decorating Streams • Summary
  • 10. Networking with Java N-10 Sockets in Java • Found in java.net package • java.net.ServerSocket  Accepts new incoming connections  Creates new ServerSocket for each connection • java.net.Socket  Connects to an existing ServerSocket, through the network
  • 11. Sockets in Java Networking with Java N-11 Host Machine Process Client Machine Process Server Socket Input Socket Output Socket Socket Socket Socket Input Socket Process Socket Client Machine
  • 12. Two new types Networking with Java N-12 • We'll be using two new types • java.net.ServerSocket • java.net.Socket  You can write to and read from a Socket's input and output streams with readObject and writeObject messages  which makes networked programs easier to develop
  • 13. Networking with Java N-13 java.net.ServerSocket • public ServerSocket(int port)  Throws IOException  Creates a ServerSocket to accept new connections at the specified port • public Socket accept()  Throws IOException  Waits for an incoming connection, establishes the new connection, and returns a socket for that connection  Multiple applications can connect to the same ServerSocket • public void close()  Throws IOException  Closes the server socket.  Does not close open sockets.
  • 14. Networking with Java N-14 java.net.Socket • public Socket(String host, int port)  Throws IOException, UnknownHostException  Connects to a server socket at the provided address (host) on the provided port • public InputStream getInputStream()  Throws IOException  Returns the input stream from the socket • public OutputStream getOutputStream()  Throws IOException  Returns the output stream from the socket • public void close()  Throws IOException  Closes the connection
  • 15. Networking with Java N-15 Building a Network app • This app will have one server and only one client (no Threads needed) • Build the server first  Need a new ServerSocket (int port)  The accept message to ServerSocket waits for a connection that knows where the server is and what port it is listening to int port = 4000; // A port available on lectura soince 2003 ServerSocket socket = new ServerSocket(port); Socket connection = socket.accept();
  • 16. Networking with Java N-16 Get the connection's streams • Let the server communicate with the connection ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
  • 17. Networking with Java N-17 Let the server read and write in loop • Let the server communicate with the connection // Take money from the client's account BankAccount theClientsAccount = null; BankAccount theServersAccount = new BankAccount("Greedy", 0.00); while (true) { double amount = ((Double) input.readObject()).doubleValue(); if (amount <= 0.0) break; theClientsAccount = (BankAccount) input.readObject(); if (theClientsAccount.withdraw(amount)) theServersAccount.deposit(amount); // Send back the modified object output.writeObject(theClientsAccount); } connection.close();
  • 18. Networking with Java N-18 Write the Client • Get the input and output stream to and friom the server we are connecting to ObjectOutputStream output = new ObjectOutputStream(server.getOutputStream()); ObjectInputStream input = new ObjectInputStream(server.getInputStream());
  • 19. Networking with Java N-19 Write the Client • Request a socket connection with the running sever // This IPAddress is for the machine where this code will run // We'll run the server and the client on the same machine for now String IPAddress = "localhost"; // There's no place like home int port = 4000; Socket server = new Socket(IPAddress, port);
  • 20. Networking with Java N-20 Let the client read and write in loop • Let the client communicate with the server // Give money to the server without knowing it BankAccount myAccount = new BankAccount("Sucker", 5000.00); boolean done = false; while (!done) { String amountAsString = JOptionPane.showInputDialog( null, "You've won! Enter desired amount" + " you have " + myAccount.getBalance()); double amount = Double.parseDouble(amountAsString); output.writeObject(new Double(amount)); if (amount > 0) { output.writeObject(myAccount); myAccount = (BankAccount) input.readObject(); } else // The user figured out how to quit done = true; } server.close();