In this Program we need two java classes named:-
1. Client.java
2. Server.java
Program:-
Client.java:-
package com.gpm.tcp_client_server;
import java.io.*;
import java.net.*;
public class Client{
private Socket client_socket = null;
private DataOutputStream output_stream = null;
public Client(String host_address,int port_number) throws
UnknownHostException,IOException{
try{
client_socket = new Socket(host_address,port_number);
System.out.println("Connected to sever");
output_stream = new DataOutputStream(client_socket.getOutputStream());
output_stream.writeUTF("Hello Server Brother");
//Closing Connections
output_stream.close();
client_socket.close(); }
catch (UnknownHostException e){
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
} }
public static void main(String args[]){
try{
String host_address = "127.0.1.1";
Client client = new Client(host_address,6060);
}
catch(UnknownHostException e){
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
}}}
Server.java:-
package com.gpm.tcp_client_server;
import java.io.DataInputStream;
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket server_socket = null;
private Socket client_socket = null;
private DataInputStream input_stream = null;
public Server(int port_number) {
try {
server_socket = new ServerSocket(port_number);
System.out.println("Server Started");
System.out.println("Waiting for client");
client_socket = server_socket.accept();
System.out.println("Client Accepted");
input_stream = new DataInputStream(new
BufferedInputStream(client_socket.getInputStream()));
String message = input_stream.readUTF();
System.out.println(message);
//CLosing connections
client_socket.close();
input_stream.close();
} catch (IOException e) {
System.out.println(e);
}
}
public static void main(String args[])
{
Server server = new Server(6060);
}
}
Output:-
Client
Server