Question

In: Computer Science

I have a problem with the code for my project. I need the two clients to...

I have a problem with the code for my project. I need the two clients to be able to receive the messages but the code I have done only the server receives the messages. I need the clients to be able to communicate with each other directly not throught the server.

The requirements of this "local chat" program must meet are:

1. The chat is performed between 2 clients and a server.

2. The server will first start up and choose a port number. Then the server prints out its IP address and port number.

3. The client then will start up and create a socket based on the information provided by the server.

4. Now the client and the server can chat with each other by sending messages over the network.

5. The client/server MUST be able to communicate with each other in a continuous manner. (e.g. One side can send multiple messages without any replies from the other side)

6. There is no requirement on what language you use to implement this project, but your program should call upon the socket API for UDP to realize the functionality.

7. You should demonstrate your project using two machines (one for the client and one for the server. Pick your virtual machine as the client to communicate with your actual machine, which is server in our project).

8. You need to open at least 2 cmd window in your virtual machine to demonstrate multiple machine communicate with your server machine (actual machine)

My Code

UDPServer.java

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

public class UDPServer {
   public static void main(String args[]) throws Exception{
       int serverport=6789;
       int clientport=1234;
       byte[] receiveData = new byte[1024];
       byte[] sendData = new byte[1024];
       DatagramSocket serverSocket = new DatagramSocket(serverport);
       System.out.println("SERVER READY");
       while(true){
       DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
       serverSocket.receive(receivePacket);
       String msg = new String(receivePacket.getData()).trim();
       System.out.println("Message from CLIENT with ID:"+msg);
        InetAddress IPAddress = receivePacket.getAddress();
       int port = receivePacket.getPort();
       String returnMsg = "Thanks. Received your message!";
       sendData = returnMsg.getBytes();
       DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
       serverSocket.send(sendPacket);
       }
   }
}

UDPClient.java

package socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
   public static void main(String args[]) throws Exception{
       int serverport=6789;
       int clientport=1234;
       byte[] sendData = new byte[1024];
       byte[] receiveData = new byte[1024];       
       BufferedReader inFromUser = new BufferedReader(   new InputStreamReader(System.in));
       String clientId;
       System.out.println("Enter your ID:");
       clientId = inFromUser.readLine();
       while(true) {
           System.out.println("Enter your message:");
           String sentence = inFromUser.readLine();
          
           DatagramSocket clientSocket = new DatagramSocket();
           InetAddress IPAddress = InetAddress.getByName("localhost");
           sendData = (clientId+":"+sentence).getBytes();
           DatagramPacket sendPacket =
                   new DatagramPacket(sendData, sendData.length, IPAddress, serverport);
           clientSocket.send(sendPacket);
           DatagramPacket receivePacket =
                   new DatagramPacket(receiveData, receiveData.length);
           clientSocket.receive(receivePacket);
           String receivedMsg = new String(receivePacket.getData()).trim();
           System.out.println("FROM SERVER:" + receivedMsg);
           clientSocket.close();
       }
   }
}

Solutions

Expert Solution

UDPClient.java


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


public class ChatClient {

static Socket s;

static int port;

static String name;

public static void main(String[] args) {

Receivemsg1 receive = new Receivemsg1();
Sendmsg1 send = new Sendmsg1();

Thread receiver = new Thread(receive);
Thread sender = new Thread(send);

try{

port = Integer.parseInt(args[2]);
s = new Socket(args[1], port);
name = args[0];
System.out.println("Connected to: " + s.getRemoteSocketAddress());
System.out.println("Welcome " + name + "!");
System.out.println("** Note: Type 'bye' and press Enter to disconnect **");
   System.out.println(">You are ready to start your chat!\n");

receiver.start();
sender.start();

}catch(IOException e){
e.printStackTrace();
}
}
}

class Sendmsg1 implements Runnable {
@Override
public void run() {
String input;
PrintWriter out = null;
  
try {
out = new PrintWriter(ChatClient.s.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
while (!(input = br.readLine()).equals("bye")){
out.println(input);
}
out.println("Client disconnected");
ChatClient.s.close();
} catch (IOException e) {
System.out.println("Disconnected");
}
}
}


class Receivemsg1 implements Runnable {
@Override
public void run() {
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(ChatClient.s.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
while((line = in.readLine()) != null) {
if(line.equals("Server disconnected")){
System.out.println("> Server: bye");
System.out.println(line);
break;
}
  
}
} catch (IOException e) {
System.out.println("Disconnected");
}
}
}

UDPServer.java

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


public class ChatServer
{

static int port;
static ServerSocket ss;
static Socket s;

public static void main(String[] args)
{

Receivemsg receive = new Receivemsg();   
Sendmsg send = new Sendmsg();

Thread receiver = new Thread(receive); //Creating thread variables
Thread sender = new Thread(send);

try{

port = Integer.parseInt(args[0]);
ss = new ServerSocket(port); //connected to given port number
System.out.println("Server Started with port: " + ss.getLocalPort());
s = ss.accept();
System.out.println("Connection Established with client: " + s.getRemoteSocketAddress());
System.out.println("** Note: Type 'bye' and press Enter to disconnect **");
   System.out.println(">You are ready to start your chat!\n");
receiver.start(); //receiver thread invoked
sender.start(); //sender thread invoked
}
catch(IOException e)
{
e.printStackTrace();
}
}
}


class Sendmsg implements Runnable {
@Override
public void run() {
String input;
PrintWriter out = null;
  
try {
out = new PrintWriter(ChatServer.s.getOutputStream(), true); //store what is to be sent as output through port
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
while (!(input = br.readLine()).equals("bye")){
out.println(input);
}
out.println("Server disconnected");
ChatServer.s.close();
} catch (IOException e) {
System.out.println("Disconnected");
}
  
}
}

class Receivemsg implements Runnable {
@Override
public void run() {
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(ChatServer.s.getInputStream())); //read the message from the socket
} catch (IOException e) {
e.printStackTrace();
}
try {
while((line = in.readLine()) != null) {
if(line.equals("Client disconnected")){
System.out.println("> Client: bye");
System.out.println(line);
break;
}
  
      
}
} catch (IOException e) {
System.out.println("Disconnected");
}
}
}

Check this! This needed lot of work and finally here! :-)


Related Solutions

In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
Hi I have a java code for my assignment and I have problem with one of...
Hi I have a java code for my assignment and I have problem with one of my methods(slice).the error is Exception in thread "main" java.lang.StackOverflowError Slice method spec: Method Name: slice Return Type: Tuple (with proper generics) Method Parameters: Start (inclusive) and stop (exclusive) indexes. Both of these parameters are "Integer" types (not "int" types). Like "get" above, indexes may be positive or negative. Indexes may be null. Description: Positive indexes work in the normal way Negative indexes are described...
Java homework problem: I need the code to be able to have a message if I...
Java homework problem: I need the code to be able to have a message if I type in a letter instead of a number. For example, " Please input only numbers". Then, I should be able to go back and type a number. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class LoginGui {    static JFrame frame = new JFrame("JFrame Example");    public static void main(String s[]) {        JPanel panel...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have to add the below requirement of calculating the expected winning probability of VCU. Revisit the program you developed for Problem 3 of Assignment 2. Now your program must calculate the expected winning probability of VCU through simulation. Run the simulation 10,000 times (i.e., play the games 10,000 times) and count the number of wins by VCU. And then, calculate the winning probability by using...
in java: In my code at have my last two methods that I cannot exactly figure...
in java: In my code at have my last two methods that I cannot exactly figure out how to execute. I have too convert a Roman number to its decimal form for the case 3 switch. The two methods I cannot figure out are the public static int valueOf(int numeral) and public static int convertRomanNumber(int total, int length, String numeral). This is what my code looks like so far: public static void main(String[] args) { // TODO Auto-generated method stub...
I need my code output values edited to be formatted to two decimal places (i believe...
I need my code output values edited to be formatted to two decimal places (i believe using setprecision), i will need you to edit my code toformat each menu option to 2 decimal places: provided is my code #include <iostream> #include <iomanip> using namespace std; int main() {    double radius;    double base;    double height;    double length;    double width;    double Area;    const double PI = 3.14159;    int choice;    // display menu   ...
I have a problem with my code. It does not run. Please can someone check the...
I have a problem with my code. It does not run. Please can someone check the code and tell me where I went wrong? This is the question: Program Specification: Write a C program that takes the length and width of a rectangular yard, and the length and width of a rectangular house (that must be completely contained in the yard specified) as input values. Assuming that the yard has grass growing every where that the house is not covering,...
This is my code I need to complete it? //The code package arraylists; import java.util.ArrayList; import...
This is my code I need to complete it? //The code package arraylists; import java.util.ArrayList; import java.util.Scanner; /** * * */ public class SoftOpening {    public static void main(String[] args) {       Scanner input = new Scanner(System.in);    ArrayList foodList = generateMenu();    User user = generateUser(input); user.introduce();    userBuyFood(foodList, user, input); user.introduce(); } public static ArrayList generateMenu(){    ArrayList foodList = new ArrayList<>();    Food pizza1 =new Food(1,"pizza","Seafood",11,12); Food pizza2 =new Food(2,"pizza","Beef",9,10); Food Friedrice =new Food(3,"fried rice","Seafood",5,12);...
in this code I have used array two times . I need a way to make...
in this code I have used array two times . I need a way to make the program functional using a string to store the results and print it again later . this game should be array free. import java.util.Scanner; import java.util.Random;//starter code provided public class inputLap { public static char roller; public static String playerName; public static int printed=0; public static int rounds=8,lives=0,randy; public static int tries[]=new int[4];//use arrays to store number of tries in each life public static...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT