Socket Programming
Socket Programming
Socket Programming
Java Networking
• Java networking (or, Java network programming) refers to writing programs that
execute across multiple devices (computers), in which the devices are all
connected to each other using a network.
• When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and
reading from the socket.
• The Socket class is used to communicate client and server. Through this class, we
can read and write message. The ServerSocket class is used at server-side. After the
successful connection of client, it returns the instance of Socket at server-side.
• The following steps occur when establishing a TCP connection between two
computers using sockets −
After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The
client's OutputStream is connected to the server's InputStream, and the
client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol; hence data can be sent across both
streams at the same time. Following are the useful classes providing complete
set of methods to implement sockets.
• Socket class
Some methods of interest in the Socket class are listed here. Notice that both
the client and the server have a Socket object, so these methods can be
invoked by both the client and the server.
S.No. Method & Description
The ServerSocket class can be used to create a server socket. This object is
used to establish communication with the clients.
When the ServerSocket invokes accept (), the method does not return until a
client connects. After a client does connect, the ServerSocket creates a new
Socket on an unspecified port and returns a reference to this new Socket. A
TCP connection now exists between the client and the server, and
communication can begin.
• We’ll create a basic client-server communication where the client sends a message
to the server, and the server reads and prints it.
Server Side:
Java
import java.io.*;
import java.net.*;
Java
import java.io.*;
import java.net.*;