给你一段代码,你看一下,希望对你有帮助
package Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
class Send
implements Runnable {
private DatagramSocket ds;
public Send(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
while ((line = bf.readLine()) != null) {
if ("886".equals(line))
break;
byte[] buf = line.getBytes();
//这里记着修改成你自己的ip,这里的端口号一定要和接收时你输入的端口号一致。
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("192.168.1.100"), 8888);
ds.send(dp);
}
} catch (Exception e) {
System.out.println("发送端口失败!");
}
}
}
class Rece implements Runnable {
private DatagramSocket ds;
public Rece(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
try {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength());
System.out.println(ip + "::" + data);
}
} catch (Exception e) {
System.out.println("接收端口失败!");
}
}
}
class ChatDemo {
public static void main(String[] args) throws Exception {
DatagramSocket sendSocket = new DatagramSocket();
//我用的是8888端口这个比较稳定那个10002老是有问题,我用的地址是我自己的,你到时候修改成你的地址就可以了。
DatagramSocket receSocket = new DatagramSocket(8888);
//正确的代码如下
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
//你的代码是这么写的,只有发送没有接收当然会有问题了
//new Thread(new Send(sendSocket)).start();
//new Thread(new Rece(sendSocket)).start();
}
} |