Question

In: Computer Science

Turn the following code into a chat system that can send messages CONTINUOSLY without the the...

Turn the following code into a chat system that can send messages CONTINUOSLY without the the other side needing to a response. Use a send and receive thread to allow this.

Client Side:

package com.company;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        byte[] receiveBytes = new byte[256];

        final String TERMINATE = "bye";
        final int SERVER_PORT = 8080;
        System.out.println("Client started. Type a message and hit Enter key to send the message to server.");
        try (Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket();) {
            // Get server address
            final InetAddress SERVER_ADDRESS = InetAddress.getLocalHost();
            DatagramPacket dataPacket = null;


            while (!ds.isClosed()) {
                String input = sc.nextLine();
                // Terminate the client if user says "bye"
                if (input.trim().equalsIgnoreCase(TERMINATE)) {
                    break;
                }


                // Construct Datagram packet to send message
                dataPacket = new DatagramPacket(input.getBytes(), input.getBytes().length, SERVER_ADDRESS, SERVER_PORT);
                ds.send(dataPacket);
                // Construct Datagram packet to receive message
                dataPacket = new DatagramPacket(receiveBytes, receiveBytes.length);
                ds.receive(dataPacket);
                System.out.println("Server Says:" + new String(receiveBytes, "UTF-8"));
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server side:

package com.company;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;
import java.net.InetAddress;

public class Main {

    public static void main(String[] args) {



        InetAddress ip;
        String hostname;


        byte[] receiveBytes = new byte[256];
        final int SERVER_PORT = 8080;



        try (DatagramSocket ds = new DatagramSocket(SERVER_PORT); Scanner sc = new Scanner(System.in);) {

            ip = InetAddress.getLocalHost();
            hostname = ip.getHostName();
            System.out.println("Your current IP address : " + ip);
            System.out.println("Your current Hostname : " + hostname);
            System.out.println("Your current Port : " + SERVER_PORT);

            System.out.println("Server started. Waiting for client message...");

            while (!ds.isClosed()) {
                // Construct Datagram packet to receive message
                DatagramPacket dp = new DatagramPacket(receiveBytes, receiveBytes.length);
                ds.receive(dp);
                String dataString = new String(dp.getData(), "UTF-8");
                System.out.println("Client Says:" + dataString);
                String input = sc.nextLine();
                // Construct Datagram packet to send message
                DatagramPacket sendPacket = new DatagramPacket(input.getBytes(), input.getBytes().length,
                        dp.getAddress(), dp.getPort());
                ds.send(sendPacket);
            }
            ds.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Solutions

Expert Solution

//------------------ Client.java
//Client Side:
package com.company;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

//this class will act as a Receiver thread
class ClientReceiver extends Thread {
    public void run() {
        byte[] receiveBytes = new byte[256];
        final String TERMINATE = "bye";
        final int RECEIVE_PORT = 8081;
        
        System.out.println("ClientReceiver started.");
        
        try (Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket(RECEIVE_PORT);) {
            DatagramPacket dataPacket = null;
            
            while (!ds.isClosed()) {
                // Construct Datagram packet to receive message
                dataPacket = new DatagramPacket(receiveBytes, receiveBytes.length);
                ds.receive(dataPacket);
                System.out.println("\t\t--- Server Says:" + new String(dataPacket.getData(), "UTF-8").trim());
                receiveBytes = new byte[256]; //reset receiveBytes array to clear previous contents
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


//this class will act as a Sender thread
public class Client {

    public static void main(String[] args) {
        ClientReceiver cr = new ClientReceiver();
        cr.start(); //start the Receiver thread

        byte[] receiveBytes = new byte[256];
        final String TERMINATE = "bye";
        final int SERVER_PORT = 8080;
        
        System.out.println("Client started.\nType a message and hit Enter key to send the message to server.");
        
        try (Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket();) {
            // Get server address
            final InetAddress SERVER_ADDRESS = InetAddress.getLocalHost();
            DatagramPacket dataPacket = null;
            
            while (!ds.isClosed()) {
                String input = sc.nextLine();
                // Terminate the client if user says "bye"
                if (input.trim().equalsIgnoreCase(TERMINATE)) {
                                        ds.close();
                                        System.exit(0);
                }
                // Construct Datagram packet to send message
                dataPacket = new DatagramPacket(input.getBytes(), input.getBytes().length, SERVER_ADDRESS, SERVER_PORT);
                ds.send(dataPacket);
                System.out.println("Client sent: " + input);
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//------------------ end of Client.java
//------------------ Server.java
//Server Side:
package com.company;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

//this class will act as a Receiver thread
class ServerReceiver extends Thread {
    public void run() {
        byte[] receiveBytes = new byte[256];
        final String TERMINATE = "bye";
        final int RECEIVE_PORT = 8080;
        
        System.out.println("ServerReceiver started.");
        
        try (Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket(RECEIVE_PORT);) {
            DatagramPacket dataPacket = null;
            
            while (!ds.isClosed()) {
                // Construct Datagram packet to receive message
                dataPacket = new DatagramPacket(receiveBytes, receiveBytes.length);
                ds.receive(dataPacket);
                System.out.println("\t\t--- Client Says:" + new String(dataPacket.getData(), "UTF-8").trim());
                receiveBytes = new byte[256]; //reset receiveBytes array to clear previous contents
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


//this class will act as a Sender thread
public class Server {

    public static void main(String[] args) {
        ServerReceiver obj = new ServerReceiver();
        obj.start(); //start the Receiver thread

        byte[] receiveBytes = new byte[256];
        final String TERMINATE = "bye";
        final int CLIENT_PORT = 8081;
        
        System.out.println("Server started.\nType a message and hit Enter key to send the message to server.");
        
        try (Scanner sc = new Scanner(System.in); DatagramSocket ds = new DatagramSocket();) {
            // Get server address
            final InetAddress CLIENT_ADDRESS = InetAddress.getLocalHost();
            DatagramPacket dataPacket = null;
            
            while (!ds.isClosed()) {
                String input = sc.nextLine();
                // Terminate the client if user says "bye"
                if (input.trim().equalsIgnoreCase(TERMINATE)) {
                    ds.close();
                                        System.exit(0);
                }
                // Construct Datagram packet to send message
                dataPacket = new DatagramPacket(input.getBytes(), input.getBytes().length, CLIENT_ADDRESS, CLIENT_PORT);
                ds.send(dataPacket);
                System.out.println("Server sent: " + input);
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
//------------------ end of Server.java


Related Solutions

You and a friend are using the C(7,4) Hamming code to send some 4-bit messages to...
You and a friend are using the C(7,4) Hamming code to send some 4-bit messages to each other. (a) You encode the message 1010 and send the encoded 7-bit sequence to your friend, who receives 1011011. How many errors were introduced during transmission? (b) You subsequently receive the encoded sequence 0111011 from your friend. Assuming at most one error, what is the 4-bit message that your friend sent?
You can estimate the total number of text messages you send and receive in a year...
You can estimate the total number of text messages you send and receive in a year as follows: Count up the number of text messages sent and received during the one-hour period of a typical day when you do the most texting; then ... Multiply that count by 13, and multiply that result by 365, the number of days in a year. 13 is a guesstimate or SWAG for the ratio of the total number of messages sent and received...
what will be the code in C programming for the client and server chat application for...
what will be the code in C programming for the client and server chat application for the below issue :- write the C Programming code that able client have a unique ID to be known by the server
A study finds that graduate students send a mean of 74 text messages per day with...
A study finds that graduate students send a mean of 74 text messages per day with a standard deviation of 15.2 text message per day while undergraduate students send a mean of 116 text messages per day with a standard deviation of 26.51. Which group, the undergraduate students or the graduate students have more variation in the number of sent text messages? Undergraduates, because their standard deviation is higher Undergraduates, because their standard deviation is lower Graduate students, because their...
1. A survey of 1000 drivers found that 29% of the people send text messages while...
1. A survey of 1000 drivers found that 29% of the people send text messages while driving. Last year, a survey of 1000 drivers found that 17% of those sent text messages while driving. (Show your work without using software to solve) a. Give a 95% confidence interval for the increase in text messaging while driving. b. At α = .05, can we conclude that there has been an increase in the number of drivers who text while driving? State...
Assuming that on average college students in the U.S. send 120 text messages per day. A...
Assuming that on average college students in the U.S. send 120 text messages per day. A researcher wants to examine if the amount of text messages sent daily by UNC students differs from the national average. The researcher took a sample of 64 UNC students, and finds that the mean number of texts per day is 126 with a standard deviation of 24. Use alpha .05 a) Is this a one-tail or two-tail test? Write appropriate hypotheses and assumptions. b)...
Continuous assurance auditing will send signals or messages deviated from an audit limit or parameter to...
Continuous assurance auditing will send signals or messages deviated from an audit limit or parameter to internal auditors. What auditing standards and methods are necessary to ensure the effectiveness and efficiency of continuous auditing services?
Email was originally designed to be used to send simple text messages. MIME has enabled the...
Email was originally designed to be used to send simple text messages. MIME has enabled the transfer of complex data types. Comment on the security versus usability of having MIME-enabled email.
Consider a scenario where Host A and Host B want to send messages to Host C....
Consider a scenario where Host A and Host B want to send messages to Host C. Hosts A and C are connected by a channel that can lose and corrupt (but not reorder) messages. Hosts B and C are connected by another channel (independent of the channel connecting A and C) with the same properties. The transport layer at Host C should alternately deliver M (M>1) consecutive messages received from A to its application layer and N (N>1) consecutive messages...
C#: If the code is the only thing that you can provide without the pictures of...
C#: If the code is the only thing that you can provide without the pictures of the form, then that is fine as well. Topics: hiding/showing controls, StatusStrip, custom event arguments, radio buttons Students will create an application that uses a dialog to create a spaceship object to populate a ListView. This ListView will be able to display in either large or small icon mode using a menu option to switch between them. Selecting a spaceship in the ListView will...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT