Copyright 2000-2019 Networking Laboratory
Java socket programming
Sungkyunkwan University
Hyunseung Choo
Computer Networks
Recap
To connect to other machine we need a socket connection. A socket
connection means the two machines have information about each
other’s network location (IP Address) and port
To communicate over a socket connection, streams are used to both
input and output the data.
Networking Laboratory 2/55
Computer Networks
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.*;
Networking Laboratory 3/55
Computer Networks
Classes
InetAddress
Socket
ServerSocket
DatagramSocket
DatagramPacket
Networking Laboratory 4/55
Computer Networks
InetAddress
Static methods you can use to create new InetAddress objects.
getByName(String host)
getAllByName(String host)
getLocalHost()
InetAddress x = InetAddress.getByName(“skku.edu”);
❖ Throws UnknownHostException
Networking Laboratory 5/55
Computer Networks
InetAddress classSample code
Uses InetAddress class to lookup hostnames found on command line.
Networking Laboratory 6/55
> java Lookup skku.edu www.yahoo.com
skku.edu:115.145.128.224
www.yahoo.com:106.10.250.11
Computer Networks
InetAddress classSample code
Try the following code:
Networking Laboratory 7/55
try {
InetAddress a = InetAddress.getByName(hostname);
System.out.println(hostname + ":" + a.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("No address found for " + hostname);
Computer Networks
Java Exceptions
When executing Java code, different errors can occur: coding errors
made by the programmer, errors due to wrong input, or other
unforeseeable things.
When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw
an exception (throw an error).
The throw statement allows you to create a custom error.
Networking Laboratory 8/55
Computer Networks
Java Exception
Networking Laboratory 9/55
try {// Block of code to try
}catch(Exception e) {
// Block of code to handle errors}
static void checkAge(int age) { if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}else {
System.out.println("Access granted - You are old enough!"); }
}
Computer Networks
Java socket programming
Standard procedure
Open a socket
Open an input stream and output stream to the socket.
Read from and write to the stream according to the server's protocol.
Close the streams.
Close the socket.
Networking Laboratory 10/55
Computer Networks
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
Networking Laboratory 11/55
Computer Networks
JAVA TCP Sockets
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()
Networking Laboratory 12/55
Computer Networks
JAVA TCP Sockets
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.
Networking Laboratory 13/55
Computer Networks
Sockets
Networking Laboratory 14/55
Figure taken from Java socket programming, Dave Hollinger and Joonbok Lee
Client socket, welcoming socket (passive) and connection socket (active)
Computer Networks
Socket Constructors
Constructor creates a TCP connection to a named TCP server
Several constructors:
Networking Laboratory 15/55
Socket(InetAddress server, int port);
Socket(InetAddress server, int port,InetAddress local, int localport);
Socket(String hostname, int port);
Computer Networks
Socket Methods
There are a lot of methods, for example:
Networking Laboratory 16/55
void close();InetAddress getInetAddress();InetAddress getLocalAddress();InputStream getInputStream();OutputStream getOutputStream();
Computer Networks
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…
Networking Laboratory 17/55
Computer Networks
InputStream Basics
Both of the followings can throw IOException and return -1 on EOF
Networking Laboratory 18/55
// reads some number of bytes and// puts in buffer array bint read(byte[] b);
// reads up to len bytesint read(byte[] b, int off, int len);
Computer Networks
OutputStream Basics
Both of the followings can throw IOException
Networking Laboratory 19/55
// writes b.length bytesvoid write(byte[] b);
// writes len bytes starting // at offset offvoid write(byte[] b, int off, int len);
Computer Networks
ServerSocket Class(TCP Passive Socket)
Constructors:
Networking Laboratory 20/55
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog, InetAddress bindAddr);
Computer Networks
ServerSocket Methods
Throw: IOException, SecurityException
Networking Laboratory 21/55
Socket accept();
void close();
InetAddress getInetAddress();
int getLocalPort();
Computer Networks
Socket programming with TCPExample client-server application
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)
Networking Laboratory 22/55o
utT
oS
erv
er
to network from network
inF
rom
Se
rve
r
inF
rom
Use
r
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
Computer Networks
Client/server socket interaction: TCP
Networking Laboratory 23/55
wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()
create socket,port=x, forincoming request:welcomeSocket =
ServerSocket()
create socket,connect to hostid, port=xclientSocket =
Socket()
closeconnectionSocket
read reply fromclientSocket
closeclientSocket
send request usingclientSocketread request from
connectionSocket
write reply toconnectionSocket
TCP connection setup
Server (running on hostid) Client
Computer Networks
TCPClient.java
Networking Laboratory 24/55
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 = newDataOutputStream(clientSocket.getOutputStream());BufferedReader inFromServer = new BufferedReader(newInputStreamReader(clientSocket.getInputStream()));sentence = inFromUser.readLine();outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); }
}
Computer Networks
TCPServer.java
Networking Laboratory 25/55
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()));
DataOutputStream outToClient = newDataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();capitalizedSentence = clientSentence.toUpperCase() + '\n’;outToClient.writeBytes(capitalizedSentence);}
}}
Computer Networks
Sample Echo Server
Check out the following implementation:
https://gist.github.com/ChrisDillinger/b717a13d367e7b99582a22c0e4bcb3
88
Networking Laboratory 26/55
Computer Networks
UDP Sockets
DatagramSocket class
DatagramPacket class needed to specify the payload
incoming or outgoing
There are no separate classes for client and server like TCP sockets.
Networking Laboratory 27/55
Computer Networks
Socket Programming with UDP
UDP
Connectionless and unreliable service.
There isn’t an initial handshaking phase.
Doesn’t have a pipe.
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.
Networking Laboratory 28/55
Computer Networks
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()
Networking Laboratory 29/55
Computer Networks
DatagramSocket Constructors
All can throw SocketException or SecurityException
Networking Laboratory 30/55
DatagramSocket();
DatagramSocket(int port);
DatagramSocket(int port, InetAddress a);
Computer Networks
Datagram Methods
Networking Laboratory 31/55
void connect(InetAddress, int port);
void close();
void receive(DatagramPacket p);
void send(DatagramPacket p);
Computer Networks
Datagram Packet
Contain the payload
(a byte array)
Can also be used to specify the destination address
when not using connected mode UDP
Networking Laboratory 32/55
Computer Networks
DatagramPacket Constructors
For receiving:
For sending:
Networking Laboratory 33/55
DatagramPacket( byte[] buf, int len);
DatagramPacket( byte[] buf, int len, InetAddress a, int port);
Computer Networks
DatagramPacket methods
Networking Laboratory 34/55
byte[] getData();void setData(byte[] buf);
void setAddress(InetAddress a);void setPort(int port);
InetAddress getAddress();int getPort();
Computer Networks
Example: Java client (UDP)
Networking Laboratory 35/55
se
nd
Pa
cke
t
to network from network
rece
ive
Pa
cke
t
inF
rom
Use
r
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
Computer Networks
Client/server socket interaction: UDP
Networking Laboratory 36/55
closeclientSocket
Server (running on hostid)
read reply fromclientSocket
create socket,
clientSocket = DatagramSocket()
Client
Create, address (hostid, port=x,send datagram request using clientSocket
create socket,port=x, forincoming request:serverSocket = DatagramSocket()
read request fromserverSocket
write reply toserverSocketspecifying clienthost address,port umber
Computer Networks
UDPClient.java
Networking Laboratory 37/55
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("localhost");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, 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();
}}
Computer Networks
UDPServer.java
Networking Laboratory 38/55
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);String sentence = new String( receivePacket.getData());System.out.println("RECEIVED: " + sentence);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);
}}
}
Computer Networks
Java URL Class
Represents a Uniform Resource Locator
scheme (protocol)
hostname
port
path
query string
Networking Laboratory 39/55
Computer Networks
URL parsing
You can use a URL object as a parser:
Networking Laboratory 40/55
URL u = new URL(“http://www.skku.edu/”);
System.out.println(“Proto:” + u.getProtocol());
System.out.println(“File:” + u.getFile());
Computer Networks
URL construction
You can also build a URL by setting each part individually:
Networking Laboratory 41/55
URL u = new URL(“http”, www.skku.edu,80,”/<your path here>/”);
System.out.println(“URL:” + u.toExternalForm());
System.out.println(“URL: “ + u);
Computer Networks
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:
Networking Laboratory 42/55
Object getContent();InputStream openStream();URLConnection openConnection();
Computer Networks
Getting Header Information
There are methods that return information extracted from
response headers:
String getContentType();
String getContentLength();
long getLastModified();
Networking Laboratory 43/55
Computer Networks
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
Networking Laboratory 44/55
Computer Networks
Java socket thread
Why we need socket thread?
To allow many clients to connect to server at a particular time,
simultaneously
Whenever a client request comes, a separate thread can be assigned
for handling each request
Networking Laboratory 45/55
https://www.geeksforgeeks.org/introducing-threads-socket-programming-java/
Computer Networks
Java socket thread
Threading overview
Networking Laboratory 46/55
Computer Networks
Java socket threadExample application
A date-time server which returns the date/time per user request
Server asks once connected:
Client enters Date/Time/Exit to get the response
Networking Laboratory 47/55
What do you want?[Date | Time]..Type Exit to terminate connection.
Computer Networks
DTserver.java
Server class
Networking Laboratory 48/55
public class Server {
public static void main(String[] args) throws IOException{
// server is listening on port 5056 ServerSocket ss = new ServerSocket(5056);
// running infinite loop for getting // client request while (true) {
Socket s = null;
try{
// socket object to receive incoming client requests s = ss.accept();
System.out.println("A new client is connected : " + s);
Computer Networks
DTserver.java
Server class
Networking Laboratory 49/55
// obtaining input and out streams DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assigning new thread for this client");
// create a new thread object Thread t = new ClientHandler(s, dis, dos);
// Invoking the start() method t.start();
} catch (Exception e){
s.close(); e.printStackTrace();
} }
} }
Tell you what happened and
where in the code it happened
Computer Networks
DTserver.java
Client handler class
Networking Laboratory 50/55
class ClientHandler extends Thread {
DateFormat fordate = new SimpleDateFormat("yyyy/MM/dd"); DateFormat fortime = new SimpleDateFormat("hh:mm:ss"); final DataInputStream dis; final DataOutputStream dos; final Socket s;
// Constructor public ClientHandler(Socket s, DataInputStream dis, DataOutputStream dos) {
this.s = s; this.dis = dis; this.dos = dos;
}
Computer Networks
DTserver.java
Client handler class
Networking Laboratory 51/55
@Overridepublic void run() {
String received; String toreturn; while (true) {
try {
// Ask user what he wants dos.writeUTF("What do you want?[Date | Time]..\n"+
"Type Exit to terminate connection.");
// receive the answer from client received = dis.readUTF();
if(received.equals("Exit")) {
System.out.println("Client " + this.s + " sends exit..."); System.out.println("Closing this connection."); this.s.close(); System.out.println("Connection closed"); break;
}
Computer Networks
DTserver.java
Client handler class
Networking Laboratory 52/55
// creating Date object Date date = new Date();
// write on output stream based on the // answer from the client switch (received) {
case "Date" : toreturn = fordate.format(date); dos.writeUTF(toreturn); break;
case "Time" : toreturn = fortime.format(date); dos.writeUTF(toreturn); break;
default: dos.writeUTF("Invalid input"); break;
} } catch (IOException e) {
e.printStackTrace(); }
}
Computer Networks
DTclient.java
Networking Laboratory 53/55
public class Client {
public static void main(String[] args) throws IOException{
try{
Scanner scn = new Scanner(System.in);
// getting localhost ipInetAddress ip = InetAddress.getByName("localhost");
// establish the connection with server port 5056 Socket s = new Socket(ip, 5056);
// obtaining input and out streams DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Computer Networks
DTclient.java
Networking Laboratory 54/55
// the following loop performs the exchange of // information between client and client handler while (true) {
System.out.println(dis.readUTF()); String tosend = scn.nextLine(); dos.writeUTF(tosend);
// If client sends exit,close this connection // and then break from the while loop if(tosend.equals("Exit")) {
System.out.println("Closing this connection : " + s); s.close(); System.out.println("Connection closed"); break;
}
// printing date or time as requested by client String received = dis.readUTF(); System.out.println(received);
}
// closing resources scn.close(); dis.close(); dos.close();
}catch(Exception e){ e.printStackTrace();
} }
}
Computer Networks
Practical Problems
1. Capitalized Server with TCP Socket or UDP Socket
2. A simple DateTime server
This is perhaps the simplest possible server. It listens on port 59090.
When a client connects, the server sends the current datetime to the client.
The connection socket is created in a try-with-resources block so it is
automatically closed at the end of the block. Only after serving the
datetime and closing the connection will the server go back to waiting for
the next client.
Networking Laboratory 55/55