Socket : A socket is a logical end point of a connection from an application programmer point of view a socket is a process that is used by the application to send and receive data over network.
A socekt manage protocal specific details on behalf of the application. To facilitate concurrent communication using different protocls, concept of qoute was introduced.
Port : A port is a numbered socket. Port Number 0 to 1024 are reserved for standard protocol such as TCP/IP, HTTP, FTP, SMTP etc.
java.net.Socket :- Class provides object representaion of TCP/IP socket that is a java application interact with TCP/IP socket through socket object. A socket object can be created using either of the following contructor.
Syntax : public Socket(String HostName, Int PortNo.)throws UnknownException,IOException;
Or
Syntax : public Socket(InetAddress Hostaddress, int portno)throws UnknownException, IOException;
Note:
First parameter of constructor represents either name of IP Address of the host on which TCP/IP server is running.
Let their be two machine name host A and host B on a network TCP/IP server is running on host B. Host A want to communicate with Host B using port 2000.
Methods of Socket Class are :-
getInputStream() : It returns an input stream to read socket data.
Syntax: public InputStream getInputStream();
getOutputStream() : Returns an outputstream to write data to socket.
Syntax: public OutputStream getOutputStream();
close() : Used to close a Socket.
Syntax: public void close();
OutputStream out = s.getOuputStream();
out.write("Hello $".getBytes());
---------------------------------------------------------------------
int n;
InputStream in = s.getInputStream();
StringBuffer str = new StringBuffer();
while(true)
{
if((n = in.read())!='$')
break;
else
str.append((char)n);
}
String s = str.toString();
PrintWriter p = new PrintWriter(s.getOutputStream());
p.print("Hello");
BufferedReader b = new BufferedReader(new InputStream(s.getInputStream());
String s = b.readLine();
java.net.ServerSocket :- Class represents the functionality of TCP/IP server. A server socket object can be created using either of the following contructor.
Syntax : public ServerSocket(int portno, int MAXQueueLenght);
Note: It's default length is 15.
accept() : Instructs the TCP/IP server to start listening connection request.
Syntax : public Socket accept();
close() :- close the TCP/IP server.
public void close();
Socket Programming in java Example.
0 Comments:
Post a Comment