TCP - Client-Server Program - Networks & DBMS Lab - Java Program

Program:

//ServerCode.java

import java.io.*;
import java.net.*;

public class ServerCode{
ServerSocket ss;
Socket socket;
BufferedReader sock_in,kdb_in;
PrintWriter sock_out;
String str;
    public ServerCode()
    {
    try{
        ss=new ServerSocket(8765);
        System.out.println("Server is listening port 8765");
        socket=ss.accept();
        System.out.println("Connection established...");
        kdb_in=new BufferedReader(new InputStreamReader(System.in));
        sock_in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sock_out=new PrintWriter(socket.getOutputStream());
        while(true)
        {
        System.out.println("Msg from client");
        str=sock_in.readLine();

        System.out.println(str);
      
        System.out.println("Enter the msg");
        str=kdb_in.readLine();
        sock_out.println(str);
        sock_out.flush();
        if(str.equals("bye"))
            break;
        }
    }catch (Exception e) { }
    }
public static void main(String arg[])
{
    new ServerCode();
}}
   
//ClientCode.java
import java.io.*;
import java.net.*;

public class ClientCode{

Socket socket;
BufferedReader sock_in,kdb_in;
PrintWriter sock_out;
String str;
    public ClientCode()
    {
    try{

        Socket socket=new Socket("127.0.0.1",8765);
        kdb_in=new BufferedReader(new InputStreamReader(System.in));
        sock_in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sock_out=new PrintWriter(socket.getOutputStream());
        while(true)
        {
       
        System.out.println("Enter the msg");
        str=kdb_in.readLine();
        sock_out.println(str);
        sock_out.flush();
        System.out.println("Msg from Server");
        str=sock_in.readLine();
        System.out.println(str);
        if(str.equals("bye"))
            break;
        }
        socket.close();
    }catch (Exception e) { }
    }
public static void main(String arg[])
{
    new ClientCode();
}}
   
Output:
Terminal 1:

students@ccflab-desktop:~$ javac ServerCode.java
students@ccflab-desktop:~$ java ServerCode
Server is listening port 8765
Connection established...
Msg from client
hai...
Enter the msg
hello...
Msg from client
bye
Enter the msg
bye
students@ccflab-desktop:~$

Terminal 2:

students@ccflab-desktop:~$ javac ClientCode.java
students@ccflab-desktop:~$ java ClientCode
Enter the msg
hai...
Msg from Server
hello...
Enter the msg
bye
Msg from Server
bye
students@ccflab-desktop:~$

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...