Introduction to Java ServerSocket
The following article provides an outline on Java ServerSocket. In web technology we have used front end and backend codes separately for creating web applications for secure purpose.Web application contains servers for receiving the client request and sent to the response for the particular request from the clients. In java technology with the help of socket programs we can achieve these task at a time we will sent the multiple request with the help of multiple pcs which has to be connected with the protocols like tcp and udp. We can write the server codes like ServerSocket class and connect with the specified ports and sent to the data’s.
Syntax:
The serversocket class is used for client and server transfer process.
Server Class:
Java packages import(import java.io.*,import java.net.*)
class serverclassname
{
public static void main(String[] args)
{
try
{
--some logic—
}
catch()
{
}
}
}
Client class:
Java packages import(import java.io.*,import java.net.*)
class clientclassname
{
public static void main(String[] args)
{
try
{
--some logic—
}
catch()
{
}
}
}
How to use Java ServerSocket?
- Java server socket connections will use the two types of protocols for sent and receive the data.
- TCP(transfer control protocol) and udp(user datagram protocol) these protocols will use the sockets class for transfer the data.
- We also see some difference between these two protocols while we use in the socket class when we use udp it means is a connection less and there is no sessions for storing the log data regarding client and server transmissions but in tcp it is a connection oriented so the client and server have the session storages in the log folders.
- The socket programs will be used for communications between the web applications running with the different jre.
- The serversocket class are mainly with the connection-oriented socket programs.
- When we connect the applications with the help of socket we need to get the informations like IP Address of the servers and port numbers which has to be connected with the applications for specified way so that the data transmission will not be interpreted.
- Basically the socket class between client and sever is the one-way data transmission so that client will sent the request messages to the server, servers read the client messages and sent the response to the client or else it will display the data to the client screen like browsers.
- So that we will use two types of java net classes are used socket and serversocket classes, the socket class is responsible for client server communications, serversocket class is used for server side applications it will authenticate the request from the client side until the client machine is connected with the socket class after the successful connections it will return the socket class instance in the server side applications.
Examples of Java ServerSocket
Given below are the examples:
Example #1
Code: Client Example
importjava.io.IOException;
importjava.io.PrintStream;
importjava.net.Socket;
importjava.net.UnknownHostException;
importjava.util.Scanner;
publicclassclientSample {
publicstaticvoidmain(String arg[]) throwsUnknownHostException,IOException
{
intn,n1;
String s;
Scanner sc=new Scanner(System.in);
Socket s1=newSocket("127.0.0.1",1408);
Scanner sc1=new Scanner(s1.getInputStream());
System.out.println("Enter any port numbers");
n=sc.nextInt();
PrintStreamp=newPrintStream(s1.getOutputStream());
p.println(n);
n1=sc1.nextInt();
System.out.println("Square of the given port number is: "+n1);
}
}
Output:
Code: Server Example
importjava.io.IOException;
importjava.io.PrintStream;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.net.UnknownHostException;
importjava.util.Scanner;
publicclassServerSample {
publicstaticvoid main(String[] args)throwsIOException {
intn,n1;
String s;
ServerSockets1=newServerSocket(1408);
Socket s2=s1.accept();
Scanner sc=new Scanner(s2.getInputStream());
s=s2.toString();
n =sc.nextInt();
n1=n*n;
PrintStreamp=newPrintStream(s2.getOutputStream());
p.println(n1);
System.out.println("Server started and working.. ");
}
}
4.8 (8,018 ratings)
View Course
Output:
Example #2
Code: Client Example
importjava.net.*;
importjava.io.*;
publicclassclientSample {
publicstaticvoid main(String[] args) throws Exception {
try{
Socket s=newSocket("127.0.0.1",8888);
DataInputStreamd=newDataInputStream(s.getInputStream());
DataOutputStreamout=newDataOutputStream(s.getOutputStream());
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
String client="",server="";
while(!client.equals("")){
System.out.println("Enter the number :");
client=br.readLine();
out.writeUTF(client);
out.flush();
server=d.readUTF();
System.out.println(server);
}
out.close();
out.close();
s.close();
}catch(Exception e){
System.out.println(e);
}
}
}
Code: Server Client
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.net.Socket;
classServerClientsextends Thread {
Socket sockets;
intclients;
intsqure;
ServerClients(Socket s,intcount){
sockets = s;
clients=count;
}
publicvoidrun(){
try{
DataInputStreaminStream = newDataInputStream(sockets.getInputStream());
DataOutputStreamoutStream = newDataOutputStream(sockets.getOutputStream());
String client="", server="";
while(!client.equals("")){
client=inStream.readUTF();
System.out.println("From Client side-" +clients+ ": Number of client is :"+client);
squre = Integer.parseInt(client) * Integer.parseInt(client);
server="From Server to Client request-" + clients + " Square of the client " + client + " is " +squre;
outStream.writeUTF(server);
outStream.flush();
}
inStream.close();
outStream.close();
sockets.close();
}catch(Exception ex){
System.out.println(ex);
}finally{
System.out.println("Client -" + clients + " exit!! ");
}
}
}
Code: Server Example
importjava.net.*;
importjava.io.*;
publicclassServerSample {
publicstaticvoid main(String[] args) throws Exception {
try{
ServerSockets=newServerSocket(8888);
intcount=0;
System.out.println("Server is Started ....");
while(true){
count++;
Socket socket=s.accept();
System.out.println(" >> " + "ClientNo:" + count + " started!");
ServerClientssc = newServerClients(socket,count);
sc.start();
}
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
Example #3
Code: Client Program
importjava.net.*;
importjava.io.*;
publicclassClientMain
{
publicstaticvoid main (String[] args ) throwsIOException {
intsize=1022388; intbytess; intc = 0;
Socket sockets = new Socket("localhost",12345);
byte [] bytes = newbyte [size];
InputStreamin = sockets.getInputStream();
FileOutputStreamout = newFileOutputStream("F:\\copy.doc");
BufferedOutputStreamb = newBufferedOutputStream(out);
bytess= in.read(bytes,0,bytes.length);
c = bytess;
do {
bytess = in.read(bytes, c, (bytes.length-c));
if(bytess>= 0) c += bytess;
}
while(bytess> -1);
b.write(bytes, 0 , c);
b.flush();
b.close();
sockets.close();
} }
Code: Server Program
importjava.net.*;
importjava.io.*;
publicclass Main
{
publicstaticvoid main (String [] args )throwsIOException
{ ServerSocketserverSockets = newServerSocket(12345);
Socket sockets = serverSockets.accept();
System.out.println("Server connection Accepted : " + sockets);
File f = new File ("F:\\Sample.docx");
byte [] bytes = newbyte [(int)f.length()];
FileInputStreaminput = newFileInputStream(f);
BufferedInputStreamb = newBufferedInputStream(input);
b.read(bytes,0,bytes.length);
OutputStreamoutput = sockets.getOutputStream();
System.out.println("Sending Files...");
output.write(bytes,0,bytes.length);
output.flush(); sockets.close();
System.out.println("File transfer complete");
} }
Output:
Conclusion
In java programming technology the package is called java.net.* In that each version of the java it may vary the classes in the package the server socket connection is basic networking feature for file transmission, upload and even though we have sent email from one client to another client with the help of socket connections
Recommended Articles
This is a guide to Java ServerSocket. Here we discuss the introduction, how to use Java ServerSocket along with respective examples. You may also have a look at the following articles to learn more –