Client Server Programming

by | Dec 18, 2020 | Java

Home » Java » Client Server Programming

Introduction

When talking about Networking and the use of Sockets to establish connections between computers in that network, only mentioning the Server-side socket would leave the process incomplete. Every client also has a socket catering to the client side of things when connecting to an application. The client socket initiates the process of establishment of a connection. In this article we will explore more about Client Server Programming.

Client Information

A client sends a connection request to a server. When the server accepts it, it is only then that a successful connection has been established. For this process to take place, a client must have the following two information about the server:

  • IP Address of the Server
  • Port Number

Example of Client Server Programming

The following Client Server program will try to illustrate client server interdependence in network programs. A client will send information to the server which it will print. The server will then send information to the client which the client will print and the process will continue until the socket is closed.

Server Side

import java.net.*;
import java.io.*;
class DemoServer
{
 public static void main(String args []) throws Exception
{
ServerSocket ss = new ServerSocket (3333);
Socket s = ss.accept();
DataInputStream din=new DataInputStream( s.getInputStream() );
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
BufferedReader br = new BufferedReader(new InputStreamReader( System.in) );

String str = "", str2= "";
while(!str.equals("stop"))
{
str = din.readUTF();
System.out.println("client says: "+str);
str2 = br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}

 

 

Client Side

import java.net.*;
import java.io.*;
class DemoClient
{
public static void main ( String args [] ) throws Exception
{
Socket s=new Socket( "localhost" , 3333);
DataInputStream din = new DataInputStream( s.getInputStream () );
DataOutputStream dout = new DataOutputStream( s.getOutputStream () );
BufferedReader br = new BufferedReader(new InputStreamReader( System.in) );

String str = "", str2 = "";
while( !str.equals("stop") )
{
str = br.readLine();
dout.writeUTF(str);
dout.flush();
str2 = din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();
}
}

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author