我正在尝试编写一个简单的控制台程序,该程序允许我发送和接收字符串消息。但我遇到的问题是我不知道如何同时运行接收代码和发送代码。
就个人而言,类(class)正在运作。我可以接收数据包并发送数据包,但让它们立即运行对我来说似乎是不可能的。
我研究过多线程,但由于我的知识仍然非常基础,我似乎无法理解它的真正工作原理。
这是我当前正在使用的代码。我自己编写了 Dialog 类,并在互联网上找到了其他两个类。
对话框类:
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;
}
}
接收类:
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);
}
}
}
发送类:
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();
}
}
}
还有,有什么方法可以测试是否可以接收数据包吗?我已经和 friend 一起测试过,但自己做会方便得多。
谢谢!
最佳答案
您没有正确使用线程。
逻辑应该在 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>
关于java - 如何同时运行这两个循环? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21704501/