Java2all.com  




Share This Topic -

socket programming in java

socket programming in java is very important topic and concept of network programming.
 
Java network Programming supports the concept of socket. A socket identifies an endpoint in a network. The socket communication take place via a protocol.
  
A socket can be used to connect JAVA Input/Output system to other programs that may resides either on any machine on the Internet or on the local machine.
 
socket programming in java
 
TCP/IP Sockets:
TCP/IP sockets are used to implement point-to-point, reliable, bidirectional, stream-based connections between hosts on the Internet.
 
There are two types of TCP sockets available in java:
(1) TCP/IP Client Socket 
(2) TCP/IP Server Socket
 
(1) TCP/IP Client Socket:
The Socket class (available in java.net package) is for the Client Socket. It is designed to connect to server sockets and initiate protocol exchange. There are two constructers used to create client sockets type object.
 
(a) Socket(String host_name,int port) throws UnknownHostException,IOException it creates a socket that is connected to the given host_name and port number.
 
(b) Socket(InetAddress ip,int port) throws IOException it creates a socket using a pre-existing InetAddress object and a port number.
 
(2) TCP/IP Server Socket:
The ServerSocket class (available in java.net package) is for the Server. It is designed to be a “listener”, which waits for clients to connect before doing anything and that listen for either local or remote client programs to connect to them on given port.
 
When you create ServerSocket it will register itself with the system as having an interest in client connection.
 
Syntax:
ServerSocket(int port) throws IOException
 
Program: Write down a program which demonstrate the Socket programming for passing the message from server to client.
 
Client.java:

 

Server.java:

 

For Output follow the below step:

(1) Run server.java

 
Console:
waiting for request....
 
(2) Run Client.java
 
Console:
waiting for request....
Request accepted
 
Input the data at server: 
 
(3) Now enter the message at console
 
Input the data at server: 
welcome at server
 
(4) Then press Enter.
 
(5) Sending a request.....
connected successfully.....
response from server...
Client side: welcome at server
 
Program 2: Write down a program for addition the two different variable by Socket programming.
 
Program 3: Write down a program which demonstrate the Socket programming for passing the message from client to server and also apply EXIT properties.