How do I run these two loops at the same time? (Java)

I am trying to write a simple console program that allows you to send and receive String messages. The problem I am facing is that I do not know how to run the receive code and the send code at the same time.

Individually, classes work. I can receive packets and send packets, but getting them to work right away seems impossible to me.

I was looking for multithreading, but since my knowledge is still very simple, I cannot understand how this works.

This is the code I'm using now. I wrote the Dialog class myself and found two other classes on the Internet.

Dialog Class:

import java.util.Scanner;


public class Dialog {

Scanner scanner = new Scanner(System.in);
User user = new User();
Network net = new Network();

ThreadReceive tr = new ThreadReceive();
ThreadSend ts = new ThreadSend();


public void run() {

    System.out.println("WELCOME");

    System.out.print("Port: ");
    while(!user.setPort(giveInput())) {
        System.out.println("Enter a valid port.");
    }

    System.out.print("IP: ");
    user.setIP(giveInput());

    System.out.println();
    System.out.println("--- CONVERSATION STARTED ---");

    tr.receive(user.getIP(), user.getPort()); // Starts receiving loop (within ThreadReceive class).

    while (true) { // Starts sending loop.
        ts.sendMessage(giveInput(), user.getIP(), user.getPort()); // Sends packet when input is given.
    }

}


private String giveInput() {

    String input = scanner.nextLine();
    return input;

}

}

Reception class:

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

public class ThreadReceive extends Thread {

public void receive(String ip, int port) {

    try {

        // Create a socket to listen on the port.
        DatagramSocket dsocket = new DatagramSocket(port);

        // Create a buffer to read datagrams into. If a
        // packet is larger than this buffer, the
        // excess will simply be discarded!
        byte[] buffer = new byte[2048];

        // Create a packet to receive data into the buffer
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        // Now loop forever, waiting to receive packets and printing them.
        while (true) {
            // Wait to receive a datagram
            dsocket.receive(packet);

            // Convert the contents to a string, and display them
            String msg = new String(buffer, 0, packet.getLength());
            System.out.println(packet.getAddress().getHostName() + ": " + msg);

            // Reset the length of the packet before reusing it.
            packet.setLength(buffer.length);
        }

    }

    catch (Exception e) {
        System.err.println(e);
    }

}

}

Dispatch Class:

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


public class ThreadSend extends Thread {

public void sendMessage(String message, String ip, int port) {

        try {
            byte[] data = message.getBytes();

            InetAddress address = InetAddress.getByName(ip);

            DatagramPacket packet = new DatagramPacket(data, data.length, address, port);

            DatagramSocket datagramSocket = new DatagramSocket();
            datagramSocket.send(packet);
        } 

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

}

Also, is there a way to check if I can receive packets? I tested it with a friend, but it would be much more convenient to do it myself.

Thank!

+3
2

Threads .

run.

queue, ArrayBlockingQueue, . ,

public void addMessage(String message) {
     synchronized(inputQueue) {
          inputQueue.offer(r);
          inputQueue.notify();
     }
}

run :

public void run() {
        try {
            while(!running) 
                    synchronized (inputQueue) {
                        inputQueue.wait();  // you can have a timeout also...
                            String message = this.inputQueue.poll();
                              // use the message item....
                              // in your case send it to the other user.
                        }
                    }       
                }
        } catch (Exception e) {
            /////// your exception handler
        }
}

, :

Thread t = new MyThread();
t.start(); /// Start the thread !!!

PS: , , - ,

Queue<String>
0

Beej : http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html - , . , , . , , ssh Linux, .

EDIT: , , . , , .

TCP, UDP, . UDP , TCP .

0

All Articles