我是一名初学者,我浏览了相关教程,但仍然不知道如何具体实现。
我有两个 while 循环,一个在 main() 方法中,一个在 send() 方法中,两者都需要同时执行,我该如何解决这个问题。
public static void main(String[] args) throws Exception
{
socket = new DatagramSocket(13373); // 69 Reserved for TFTP
// Listen for incoming packets
while(true) {
// Do things
}
}
private static void sendDATA() {
while(true) {
// Do things
}
}
sendDATA 中的 while 循环的工作原理是从文件中读取 512 字节,然后将它们发送到客户端类。虽然主方法中的循环接收来自客户端的数据包并更新变量(如果变量为 true),则 sendDATA 读取接下来的 512 字节并发送它们,依此类推,但我无法在两个线程中工作。
我已经用一个 while 循环完成了这一点,并且程序可以正常工作,它可以传输除最后一个之外的所有数据包。客户端永远不会收到最后一个数据包。
服务器:
public static void main(String[] args) throws Exception
{
socket = new DatagramSocket(13373); // 69 Reserved for TFTP
// Listen for incoming packets
while(true) {
DatagramPacket packet = new DatagramPacket(incoming, incoming.length);
socket.receive(packet);
clientip = packet.getAddress().toString().replace("/", "");
clientport = packet.getPort();
System.out.println(clientport);
if(incoming[0] == 1 || incoming[0] == 2) {
handleRequest(incoming);
}
}
}
// sends DATA opcode = 3 : | opcode | block # | data |
private static void sendDATA() {
try {
ByteBuffer sDATA = ByteBuffer.allocate(514);
byte[] tmp = new byte[512];
DatagramPacket data = new DatagramPacket(sDATA.array(), sDATA.array().length, InetAddress.getByName(clientip), clientport);
InputStream fis = new FileInputStream(new File(FILE));
int a;
int block = 1;
while((a = fis.read(tmp,0,512)) != -1)
{
data.setLength(a);
sDATA.put((byte)3);
sDATA.put((byte)block);
System.out.println(sDATA.array().length);
sDATA.put(tmp);
System.out.println(tmp.length);
socket.send(data);
socket.setSoTimeout(60000);
while(true) {
DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
try {
socket.receive(getack);
if(incoming[0] == 4 && incoming[1] == block) {
break;
} else if(incoming[0] == 4 && incoming[1] == block && tmp.length < 511) {
fis.close();
break;
}
} catch (SocketTimeoutException e) {
socket.send(data);
continue;
}
}
block++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
客户:
public static void main(String[] args) throws Exception
{
clientSocket = new DatagramSocket(8571);
// WRQ || RRQ
Scanner input = new Scanner(System.in);
int opcode = input.nextInt(); input.close();
// Pripravi paketek
outgoing = makeRequestPacket(opcode,"filename.txt","US-ASCII");
// Odposlje pakete
sendPacket(outgoing);
// Streznik vrne ACK - opcode 4 ali ERROR - opcode 5
// Pri ACK zacnemo posiljat DATA opcode 3 drugace prekinemo povezavo ob ERROR - opcode 5
while(true) {
DatagramPacket receiveResponse = new DatagramPacket(incoming, incoming.length);
clientSocket.receive(receiveResponse);
// opcode 5 - ERROR
if(incoming[0] == 5) {
getError(incoming);
}
else if(incoming[0] == 4 && incoming[1] == 0) { // opcode 4 - Prvi ACK
System.out.print("opcode: (" + incoming[0] +") ACK received operation confirmed.");
continue;
}
else if(incoming[0] == 3) {
System.out.println("Ah got a data packet.");
File initfile = new File("filename2.txt");
if(!initfile.exists()) {
initfile.createNewFile();
}
int block;
FileOutputStream fio = new FileOutputStream(initfile);
if(incoming.length > 511) {
block = incoming[1];
System.out.println("Will start to write.");
for(int i = 2; i < incoming.length; i++) {
fio.write(incoming[i]);
}
ByteBuffer recack = ByteBuffer.allocate(514);
recack.put((byte)4);
recack.put((byte)block);
System.out.println("If i came here and nothing happened something went horribly wrong.");
DatagramPacket replyACK = new DatagramPacket(recack.array(), recack.array().length, InetAddress.getByName("localhost"),13373);
clientSocket.send(replyACK);
} else if (incoming.length < 511) {
System.out.println("Last chunk.");
block = incoming[1];
for(int j = 2; j < incoming.length; j++) {
if(incoming[j] != 0) {
fio.write(incoming[j]);
} else {
break;
}
}
ByteBuffer recack = ByteBuffer.allocate(514);
recack.put((byte)4);
recack.put((byte)block);
DatagramPacket replyACK = new DatagramPacket(recack.array(), recack.array().length, InetAddress.getByName("localhost"),13373);
clientSocket.send(replyACK);
fio.close();
clientSocket.close();
break;
}
continue;
}
}
}
最佳答案
您必须使用阻塞 channel 才能同步进程之间的通信:
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
更多信息:http://docs.oracle.com/javase/1.4.2/docs/api/java/nio/channels/SocketChannel.html
此外,套接字被设计为在进程之间发送数据,如果不是这种情况,您的方法是错误的,您应该更改您的设计,即当(或每次)数据准备好时调用新线程中的每个循环(每个线程将处理其数据然后死亡)或者如果不需要并发执行,则只需在一个循环内按顺序执行两个指令 block 。程序的状态图可以帮助您确定哪个是最佳解决方案。
关于Java 线程 - 两个 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12365871/