Categories
TE Computer Engineering

10. Write a program using TCP sockets for wired network to implement a. Peer to Peer Chat

Download write-up here

//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”,8080);
        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
unixlab@unixlab-Veriton-M200-H81:~$ javac ClientCode.java
unixlab@unixlab-Veriton-M200-H81:~$ java ClientCode
Enter the msg
hiiii
Msg from Server
hii,welcome to svit
Enter the msg
what r u doing?
Msg from Server
nothing
Enter the msg
ok bye
Msg from Server
bye
unixlab@unixlab-Veriton-M200-H81:~$
*/

//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(8080);
        System.out.println(“Server is listening port 8080”);
        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();
}
}

/* Output:
unixlab@unixlab-Veriton-M200-H81:~$ javac ServerCode.java
unixlab@unixlab-Veriton-M200-H81:~$ java ServerCode
Server is listening port 8080
Connection established…
Msg from client
hiiii
Enter the msg
hii,welcome to svit
Msg from client
what r u doing?
Enter the msg
nothing
Msg from client
ok bye
Enter the msg
bye
unixlab@unixlab-Veriton-M200-H81:~$
*/

Leave a Reply

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