Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Chapter 5

Networking /
Socket Programming
Summery of your comments
• Issues that I accept: Last but not least:
• Lab=5 ስትቀልድ ጩባውን ትመስላለህ?
• Blackboard=2
• Let’s discuss & decide together:
• Quiz (-ve=3, +ve=2):-
• Speed of teaching (-ve=2,+=2):-
• Slide (-ve=1, +ve=2):-
• Sudden decision: Quiz + tearing paper (-ve=1):-
• Needs my reflection:
• Test, final exam & grade related (6)
• About other instructors (4)
• You are good instructor (Thank you very much!)

AP, By: Wondwossen E. 2


Contents
 Introduction
 Client/Server Computing
❑ Server Sockets
❑ Client Sockets
❑ Data Transmission through Sockets
❑ A Client/Server Example
 The InetAddress Class
 Serving Multiple Clients
 Sending and Receiving Objects

AP, By: Wondwossen E. 3


Introduction
 IP Address:
❑ To communicate each other computer, they should have unique address.
❑ An Internet Protocol (IP) address uniquely identifies computers on the Internet.
❑ IP is a low-level protocol for delivering data from one computer to another across the Internet in
packets.
❑ Two higher-level protocols are used in conjunction with the IP:
❖ the Transmission Control Protocol (TCP) and
❖ the User Datagram Protocol (UDP).
 TCP guarantees delivery of data and also guarantees that packets will be delivered in the same order in
which they were sent.
 UDP is a standard, low-overhead, connectionless, host-to-host protocol that is used over the IP.
 Java supports both stream-based and packet-based communications.
❑ Stream-based communications use TCP for data transmission.
❑ packet-based communications use UDP.
 Since TCP can detect lost transmissions and resubmit them, transmissions are lossless and reliable.
 UDP, in contrast, cannot guarantee lossless transmission.
 Stream-based communications are used in most areas of Java programming and are the focus of this
chapter.
AP, By: Wondwossen E. 4
Client / Server Computing
 Java provides two important class:
❑ ServerSocket – class for creating a server socket and
❑ Socket – class for creating a client socket.
✓Both classes are in package java.net You need to import them from this package.
 Two programs on the Internet communicate through a server socket and a client socket using
I/O streams.
 Sockets are the endpoints of logical connections between two hosts and can be
used to send and receive data.
 Programs can read from or write to sockets the same way they read from or write
to files.
 Network programming usually involves a server and one or more clients.
❑ The client sends requests to the server, and the server responds, i.e.
▪ The client begins by attempting to establish a connection to the server.
▪ The server can accept or deny the connection.
❑ Once a connection is established, the client and the server communicate through sockets.
✓ The server must be running when a client attempts to connect to the server.

AP, By: Wondwossen E. 5


Client / Server Computing
 A socket is one 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 is destined to.
 An endpoint is a combination of an IP address and a port number.
 Every TCP connection can be uniquely identified by its two endpoints. That way
you can have multiple connections between your host and the server.
 The Socket class, implements one side of a two-way connection between your
Java program and another program on the network.
❑ The Socket class sits on top of a platform-dependent implementation, hiding the details of the
underlying system.
❑ By using the Socket class, your Java programs can communicate over the network in a
platform-independent fashion.
 The ServerSocket class implements a socket that servers can use to listen for and
accept connections to clients.

6
AP, By: Wondwossen E.
Client / Server Computing
 Simple steps for creating Client/Server Computing is
1. The Server creates a socket bound to a specific port number
2. The Server listens to the socket for a client to make connection.
3. The client tries to connect to the server by specifying the hostname (IP) and port
number on which the server is running.
4. If everything goes well, the server accepts the connection
❖ Upon acceptance, the server gets a new socket bound to the same local port and also has its
remote endpoint set to the address and port of the client.
❖ It needs a new socket so that it can continue to listen to the original socket for connection
requests while tending to the needs of the connected client.
5. On the client side, if the connection is accepted, a socket is successfully created
and the client can use the socket to communicate with the server.
6. The client and server can now communicate by writing to or reading from their
sockets.

AP, By: Wondwossen E. 7


Client / Server Computing

AP, By: Wondwossen E. 8


Server Sockets
 To establish a server:
 Create a server socket and attach it to a port, which is where the
server listens for connections.
 Port numbers range from 0 to 65536, but port numbers 0 to 1024
are reserved for privileged services. (E.g. Email servers run on 25,
Web server run on port 80).
 Code: ServerSocket serverSocket = new ServerSocket(port);
 NB: Attempting to create a server socket on a port already in use would cause a
java.net.BindException. (Either handle it or throw it).
 After a server socket is created, the server can use the following statement to listen
for connections:,
 Code: Socket socket = serverSocket.accept();
AP, By: Wondwossen E. 9
Methods of the ServerSocket Class
• socket accept() -- Accepts an incoming connection.
• int getLocalPort() -- Returns the port number on which
the server socket is listening.
• void close() -- Closes the server socket.

AP, By: Wondwossen E. 10


Client Sockets
 The client issues the following statement to request a connection to a server:
Socket socket = new Socket(serverName, port);
❑ This statement opens a socket so that the client program can communicate
with the server. serverName is the server’s Internet host name or IP address.
❑ The following statement creates a socket on the client machine to connect
to the host 130.254.204.33 at port 8000:
Socket socket = new Socket("130.254.204.33", 8000); //OR
Socket socket = new Socket(“hu.edu.et", 8000);
 A program can use the host name localhost or the IP address
127.0.0.1 to refer to the machine on which a client is running.
❑ The Socket constructor throws a java.net.UnknownHostException
if the host cannot be found.
AP, By: Wondwossen E. 11
Methods of the Socket Class
• InetAddress getInetAddress() -- Returns the InetAddress that is associated
with the socket object.
• int getPort() -- Returns the port number on which the socket is connected (the
other sockets port)
• int getLocalPort() -- Returns the local port number on which the socket is
created (its own port)
• SocketAddress getLocalSocketAddress() --Returns the address of the endpoint
this socket is bound to.
• InputStream getInputStream() -- Returns the InputStream associated with the
calling object.
• OutputStream getOutputStream() -- Returns the OutputStream associated
with the calling object.
• void close() -- Closes the InputStream() and OutputStream() of the socket.

AP, By: Wondwossen E. 12


Basic Steps to Make it All Happen
 The basics are much the same
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream.
4. Close the streams.
5. Close the socket

AP, By: Wondwossen E. 13


Example: It just creates the connection
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket srvSkt = new ServerSocket(1122);
System.out.println(“Waiting for client’s connection request..");
Socket skt = srvSkt.accept();
System.out.println(“Connection Successful!”);
} catch (Exception e) {
System.out.println(“Connection Problem Occurred!”);
}
}
}
--------------------------------------------------------------------------------------------------------------------------
public class Client {
public static void main(String[] args) {
try {
Socket skt = new Socket("localhost",1122);
System.out.println(“Connected to server!”);
} catch (Exception e) {
System.out.println(“Connection Problem Occurred!”);
}
}
} AP, By: Wondwossen E. 14
Chat Example: Server
public class MyServer {
public static void main(String[] args) throws
Exception { Scanner sc = new Scanner(System.in);
ServerSocket srvSkt = new ServerSocket(1122); while (true) {
System.out.println("Waiting for client.."); System.out.print("Me: ");
msg = sc.nextLine();
Socket skt = srvSkt.accept();
dout.writeUTF(msg);
System.out.println("Successful!"); System.out.println("Client: " +
DataInputStream din = new din.readUTF());
DataInputStream(skt.getInputStream()); }
DataOutputStream dout = new }
DataOutputStream((skt.getOutputStream())); }
String msg;

AP, By: Wondwossen E. 15


Chat Example: Client
import java.io.*; import java.net.Socket; import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
Socket skt = new Socket("localhost", 1122);
System.out.println("Connected to server!");
DataInputStream din = new DataInputStream(skt.getInputStream());
DataOutputStream dout = new DataOutputStream((skt.getOutputStream()));
String msg;
Server Client
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Server: " + din.readUTF()); din din
System.out.print("Me: ");
msg = sc.nextLine();
dout.writeUTF(msg);
} dout dout
}
}
AP, By: Wondwossen E. 16
Assignment 3 ?%
• Create a client/server application that allows to chat using GUI.

AP, By: Wondwossen E. 17

You might also like