L2 Sockets
L2 Sockets
1
Agenda
Introduction
Networking Basics
Understanding Ports and Sockets
Java Sockets
Implementing a Server
Implementing a Client
Sample Examples
Conclusions
2
Introduction
3
Internet Applications Serving Local
and Remote Users
PC client
Internet
Server
Local Area Network
PDA
4
Increasing Demand for Internet
Applications
To take advantage of opportunities presented by
the Internet, businesses are continuously seeking
new and innovative ways and means for offering
their services via the Internet.
This created a huge demand for software
designers with skills to create new Internet-enabled
applications or migrate existing/legacy applications
to the Internet platform.
Object-oriented Java technologies—Sockets,
threads, RMI, clustering, Web services—have
emerged as leading solutions for creating portable,
efficient, and maintainable large and complex
Internet applications.
5
Elements of Client-Server
Computing/Communication
a client, a server, and network
network
client
server
Processes follow protocols that define a set of rules that must be observed by participants:
How the data exchange is encoded?
How events (sending, receiving) are synchronized (ordered) so that participants can send and receive data in a
coordinated manner?
In face-to-face communication, humans beings follow unspoken protocols based on eye contact,
body language, gesture.
6
Networking Basics
Physical/Link Layer TCP/IP Stack
Functionalities for transmission of
signals representing a stream of
data from one computer to
another
Internet/Network Layer Application
IP (Internet Protocols) – a packet (http,ftp,telnet,…)
of data to be addressed to a
remote computer and delivered Transport
Transport Layer (TCP, UDP,..)
Functionalities for delivering data
packets to a specific process on Internet/Network
a remote computer
TCP (Transmission Control (IP,..)
Protocol)
UDP (User Datagram Protocol) Physical/Link
Programming Interface: (device driver,..)
Sockets
Applications Layer
Message exchange between
standard or user applications:
HTTP, FTP, Telnet, Skype,… 7
Networking Basics
9
TCP Vs UDP Communication
A … B
Connection-Oriented Communication
A
… B
Connectionless Communication
10
Understanding Ports
13
Socket Communication
Connection request
port
server Client
14
Socket Communication
server
port
Client
port Connection
15
Sockets and Java Socket Classes
Input/read stream
Socket(“128.250.22.134”, 1234)
It can be host_name like “clouds.cis.unimelb.edu.au” 17
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("Hello\n");
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.
} 18
Implementing a Client
19
A simple server (simplified code)
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}
20
A simple client (simplified code)
// SimpleClient.java: a simple client program
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1234
Socket s1 = new Socket(“clouds.cis.unimelb.edu.au",1234);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}
21
Run
Run Server on mundroo.cs.mu.oz.au
[raj@mundroo] java SimpleServer &
22
Socket Exceptions
try {
Socket client = new Socket(host, port);
handleConnection(client);
}
catch(UnknownHostException uhe) {
System.out.println("Unknown host: " + host);
uhe.printStackTrace();
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
23
ServerSocket & Exceptions
24
Server in Loop: Always up
// SimpleServerLoop.java: a simple server program that runs forever in a single thead
import java.net.*;
import java.io.*;
public class SimpleServerLoop {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
while(true)
{
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}
}
25
Java API for UDP Programming
DatagramSocket
26
UDP Client: Sends a Message and
Gets reply
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main(String args[]){
// args give message contents and server hostname
// "Usage: java UDPClient <message> <Host name> <Port number>"
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = 6789; // Or Integer.valueOf(args[2]).intValue() if use <Port number> args[2]
DatagramPacket request = new DatagramPacket(m, args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()));
}
catch (SocketException e){System.out.println("Socket: " + e.getMessage());}
catch (IOException e){System.out.println("IO: " + e.getMessage());}
finally
{
if(aSocket != null) aSocket.close();
}
}
} 27
UDP Sever: repeatedly received a
request and sends it back to the client
import java.net.*;
import java.io.*;
public class UDPServer{
public static void main(String args[]){
DatagramSocket aSocket = null;
try{
aSocket = new DatagramSocket(6789); // fixed port number
byte[] buffer = new byte[1000];
while(true){
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),
request.getLength(), request.getAddress(), request.getPort());
aSocket.send(reply);
}
}catch (SocketException e){System.out.println("Socket: " + e.getMessage());}
catch (IOException e) {System.out.println("IO: " + e.getMessage());}
finally {if(aSocket != null) aSocket.close();}
}
}
28
Multithreaded Server: For Serving
Multiple Clients Concurrently
Server Process
Client Process 2
Server threads
Client Process 1
29
Summary
31