我编写了一个小型 UDP 客户端,它将数据包发送到某个本地地址,另一个小型 UDP 客户端将接收它们并在控制台上打印它的包含。他们目前不工作,我不知道为什么。
这是发送代码:
import java.io.*;
import java.net.*;
class ClienteUDPtx {
static final String HOST = "192.168.1.201";
static final int PUERTO=20001;
/**
UDP Client which will send some UDP packets
to local network address 192.168.1.201 on port 20001
*/
public ClienteUDPtx( ) {
try{
int i = 0;
String[] ip_parts = HOST.split(".");
byte[] ip_num = {0, 0, 0, 0};
for (String string : ip_parts) {
ip_num[i++] = Byte.valueOf(string);
}
InetAddress ip = InetAddress.getByAddress(ip_num);
DatagramSocket skCliente = new DatagramSocket(PUERTO, ip);
DatagramPacket packet;
File testFile = new File("test.txt");
BufferedReader input = new BufferedReader(new FileReader(testFile));
String line;
while((line=input.readLine())!=null) {
System.out.println("Sending: " + line);
byte message[] = line.getBytes();
packet = new DatagramPacket(message, message.length, ip, PUERTO);
skCliente.send(packet);
Thread.currentThread().sleep(1000);
}
line = "END";
System.out.println("Sending: " + line);
byte message[] = line.getBytes();
packet = new DatagramPacket(message, message.length, ip, PUERTO);
skCliente.send(packet);
input.close();
skCliente.close();
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new ClienteUDPtx();
}
}
这是接收代码:
import java.io.*;
import java.net.*;
class ClienteUDPrx {
static final String HOST = "192.168.1.101";
static final int PUERTO=20001;
/**
UDP Client which will listen for incoming UDP packets
from local network address 192.168.1.101 on port 20001
and will print its content on console
*/
public ClienteUDPrx( ) {
try{
int i = 0;
String[] ip_parts = HOST.split(".");
byte[] ip_num = {0, 0, 0, 0};
for (String string : ip_parts) {
ip_num[i++] = Byte.valueOf(string);
}
InetAddress ip = InetAddress.getByAddress(ip_num);
DatagramSocket skCliente = new DatagramSocket(PUERTO, ip);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while(true){
// Wait to receive a datagram
skCliente.receive(packet);
String lineaLeida = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "+ lineaLeida);
if(lineaLeida.equals("END")) break;
}
skCliente.close();
System.out.println( "Transmission ended" );
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new ClienteUDPrx();
}
}
任何想法?