freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Socket:-

1) Socket is used to create the connection between the client and server.
2) Socket is nothing but a combination of IP Address and port number.
3) The socket is created at client side.
4) Socket is class present in the java.net package
5) It is acting as a communicator between the client and server.
6) Whenever if we want to send the data first we have to create a socket that is acts as a medium.
Create the socket
1) Socket s=new Socket(int IPAddress, int portNumber);
a. Socket s=new Socket(“125.125.0.5”,123);

2) Socket s=new Socket(String HostName, int PortNumber);
a. Socket s=new Socket(Durgasoft,123);

client socket

import java.net.*;
import java.io.*;
class Client
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("localhost",5555);
String str="ratan from client";
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.println(str);
InputStream is=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str1=br.readLine();
System.out.println(str1);
}
}

intput and output

server program

class Server
{
public static void main(String[] args) throws Exception
{
//to read the data from client
ServerSocket ss=new ServerSocket(55);
Socket s=ss.accept();
System.out.println("connection is created ");
InputStream is=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String data=br.readLine();
System.out.println(data);
//write the data to the client
data=data+"this is from server";
OutputStream os=s.getOutputStream();
PrintStream ps=new PrintStream(os);
ps.println(data);
}

intput and output

connection is created
hi
hi this is from server(in client prohram)