Creating a Socket to Display Message to a Single Client in Java
Last Updated :
25 Mar, 2022
This article describes the basic client-server connection where a client connects, a server sends a message to the client and the client displays the message using a socket connection. A client program sockets establish a connection with the server socket of server application then server socket connects with internal sockets in the server application.
Client-Side Program
Client program uses Socket class to establish a connection with a server. Socket object needs the address of the server and the port number of the server.
Java
import java.io.*;
import java.net.*;
class GFG {
public static void main(String[] args)
{
try {
Socket socket = new Socket( "localhost" , 1346 );
System.out.println(
"Connected Successfully....." );
BufferedReader bs = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
System.out.println( "Response from Server....." );
System.out.println( "Client Side : "
+ bs.readLine());
socket.close();
}
catch (UnknownHostException e) {
System.out.println( "IP not found for" + e);
}
catch (IOException e) {
System.out.println( "Not found data for socket"
+ e);
}
}
}
|
Server-Side Program
Server program uses a Server Socket class to establish a connection with the client. Server Socket object needs the port number.
Java
import java.io.*;
import java.net.*;
class GFG {
public static void main(String[] args)
{
try {
ServerSocket serversocket
= new ServerSocket( 1346 );
System.out.println( "waiting for request...." );
Socket socket = serversocket.accept();
System.out.println( "Request Accepted..." );
PrintStream ps
= new PrintStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println(
"Input the data at the server..." );
ps.print(br.readLine());
socket.close();
serversocket.close();
}
catch (IOException e) {
System.out.println( "Not found data for socket"
+ e);
}
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...