Class Socket in Java

0
44
Spread the love
  • 29
  • 34
  • 24
  • 23
  •  
  •  
  •  
  • 12
  •  
  •  
    122
    Shares

Socket(Client) in Java
Socket(Client) in Java

Socket(Client) in Java

Java’s socket interface provides access to the standard network protocols used for communication between hosts and Internet.

Sockets are low level programming interface for networked communications. They send streams of data between applications that may or may not be on the same host.

Java.net.Socket class represents a single side of the socket connection and either the client or server. The server uses java.net.ServerSocket class to wait for connection from clients.

Clientsocket and Server Socket
Clientsocket and Server Socket

Java supports a simplified object oriented interface to sockets that makes network communications easier.Java also provides different kinds of sockets to support two distinct classes of underlying protocols.

Connection-Oriented Protocol

A connection oriented protocol establishes a connection between sender and receiver first. Once the connection is made, two applications can send data back and forth.

The connection stays even if no data exchange takes place.The protocol ensures that no data is lost and that is always arrive in order.

A TCP/IP is a connection oriented protocol.

Connection less Protocol

Datagram Socket class on the other hand uses a connection less protocol.A connection less protocol is more like a postal service.Applications can send short messages to each other but it does not attempt to keep the connection open between messages.

Datagram Socket does not guarantee that the order of the message or it does not keep track if the message has been delivered or not or arridev or not.

UDP is a connection less protocol.

Socket class implements client socket for inter process communication over network.A Socket is an end point for communication between two machines.The actual work of the socket is performed by an instance of the SocketImpl class.An application ,by changing the socket factory that creates the socket implementation,can configure itself to create socket appropriate to local firewall.

The client obtains a Socket Object by instantiating one,Whereas the server obtains a Socket object from return value of accept() method.When the Socket constructor returns , it does not instantiate a Socket object but actually tries to connect to the specified Server and port.

The constructor methods create the socket and connects to the specified host and port. We can also specify if the communication will be on the connection based Stream protocol or using a datagram protocol.

A datagram based protocol is unreliable but faster.A Stream based protocol is chosen by default. Once the socket is created we can use the getInputStream() for file input and getOutputStream for file file output.

The structure of  class Socket is given as:


public final class java.net.Socket extends java.lang.Object{
//constructors
public Socket(InetAddress address,int port) throws IOException;
public Socket(InetAddress address,int port,boolean stream) throws IOException;
public Socket(String host,int port) throws UnknownHostException;
public Socket(String host,int port,boolean stream) throws IOException;
public Socket(String host,int port,InetAddress localAddress,int localPort) throws IOException;
public Socket(InetAddress address,int port,InetAddress loalAddress,int localPort)throws IOException;
protected Socket();
protected Socket(SocketImpl impl) thows SocketException;
//methods
public synchronized void close();//closes the Socket. This makes the socket object no longer 
//capable of connecting again to any server.
public InetAddress getInetAddress();//this method returns the address of the other computer
//that this socket is connected to.
public InputStream getInputStream() throws IOException;//Returns the input stream of the 
//Socket.The input stream is connected to the output stream of the socket.
public int getLocalPort();//returns the port the socket is bound to on the local machine.
public int getPort();//returns the port of the socket is bound to on the remote machine.
public static void setSocketImplFactory(SocketImplFactory fac);
public OutputStream getOutputStream() throws IOException;//Returns the output stream 
//of the socket The output stream is connected to the input stream of the remote socket.
public SocketAddress getRemoteSocketAddress();//returns the address of the remote socket.
public void connect(SocketAddress host,int timeout) throws IOException;//This method 
//connects the socket to the specified host.This method is needed only when we 
//instantiate the Socket using the no argument constructor.
public String toString();
public static synchronized void setSocketImplFactory(SocketImplFactory fac) throws IOException;
public InetAddress getLocalAddress();
public int getSoLinger() throws SocketException;
public synchronized int getSoTimeOut() throws SocketException;
public boolean getTcpNoDelay() throws SocketException;
public void setSoLinger(boolean on,int value) throws SocketException;
public synchronized void setSoTimeout(int timeout)  throws SocketException;
public void setTcpNoDelay(boolean on) throws SocketException;
}
 

public Socket(InetAddress address,int port) throws IOException, UnknownHostException :

Creates a StreamSocket and connects it to the specified port number at the specified IP address(host). If the application has specified a socket factory,the factory’s createSocketImpl() method is called to create the actual socket implementation.Otherwise a plain socket is created.It may throw IOException if an I/O error occurs while opening the socket or creating the socket.It may also throw UnknownHostException if the host can not be resolved.It the constructor does not throw any exception,it means that the connection is successful.

public Socket(InetAddress address,int port,boolean stream)

Creates a socket and connects it to the specified port number at the specified IP address.If the stream argument is true ,this creates a Stream socket.If false it creates a DatagramSocket. It may throw IOException if an I/O error occurs while opening the socket or creating the socket.

public Socket(String host,int port)throws IOException

Creates a stream socket and connects it to the specified port number on the named host.It may throw IOException if an I/O error occurs while opening the socket or creating the socket.

public Socket(String host,int port,boolean stream)throws IOException

Creates a stream socket and connects it to the specified port number on the named host.If the stream argument is true ,this creates a Stream socket.If false it creates a DatagramSocket. It may throw IOException if an I/O error occurs while opening the socket or creating the socket.

public Socket(String host,int port,InetAddress localAddress,int localPort)throws IOException

Connects to the specified host and port,creating a socket on the local host at the specified address and port.

public Socket(String host,int port,InetAddress localAddress,int localPort)throws IOException

This is almost equivalent to the previous one except that the host is denoted by an InetAddress Object instead of String.

How to connect to server?

A client application opens a connection to a server by constructing a socket that specifies the host name and port number of the desired server.

try{
Socket sock=new Socket("techtravelhub.com",99);
}
catch(UnknownHostException e)
{
System.out.println("Can not find host");
}
catch(IOException e)
{
System.out.println("Error connecting to host");
}

This code attempts to connect a socket at port 99 of the host techtravelhub.com.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 29
  • 34
  • 24
  • 23
  •  
  •  
  •  
  • 12
  •  
  •  
    122
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here