解决了没有?没有就给个简单的答案给你参考哈哈(记得给分哦): 思想就是你想的那样用随机端口的方案:(由于这个端口要求是1024以上的哈)在登录页面(LoginInterface.java)加上这个函数:public int getrandomport() {
int port = 0;
Random rm = new Random();
int j = 0;
for (i = 0; i < 10; i++) {
j = rm.nextInt(20000);
if (j > 1111) {
port = j;
}
}
return port;
} 将这个函数的返回值用一个静态变量保存起,以备我们在日后UDPchat.java上使用,同时我们将其放入到用户登录时的USer表中port列下。 ...................................port =String.valueOf(getrandomport());
String updatesql = "update user set status='" + status + "',tmpip='" + tmpip + "',tmpport='" + port + "'where usr_id='" + usr_id + "' ";
st.executeUpdate(updatesql);.................................. 在UDPchat页面的构造方法中new 以个thread:用来接收别人发来的数据。其监听端口为自己登陆时所产生的那个随机端口new Thread() {// receive data
public void run() {
DatagramSocket ds = null;
try {
int acceptport = Integer.parseInt(LoginInterface.port);
ds = new DatagramSocket(acceptport);
} catch (Exception e1) {
e1.printStackTrace();
}
byte[] data = new byte[1024];
DatagramPacket dp = new DatagramPacket(data, data.length);
while (true) {
try {
ds.receive(dp);
String ip = new String(dp.getAddress().getHostAddress());
String port = String.valueOf(dp.getPort());
String str = new String(dp.getData());
String sum = "From: " + ip + " Port:" + port
+ " receive data: " + str;
receives.add(sum, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start(); 另外构造一个send 方法用来发送自己的消息:部分代码如下:.............................try {
// send data
if (sends.getText().equals("")) {
JOptionPane.showMessageDialog(null, "输入内容不能为空");
} else {
int port = Integer.parseInt(MainInterface.port);
byte[] buf = sends.getText().getBytes();
InetAddress address = InetAddress.getByName(MainInterface.ip);
DatagramPacket dp = new DatagramPacket(buf, buf.length,
address, port);// destinate port
ds.send(dp);
receives.add("我说: " + sends.getText(), 0);
sends.setText("");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ds.close();
}................................此处的MainInterface.ip和MainInterface.port是当我们双击面板上的某个欲和他聊天的用户(根据好友名字从数据库中取出的好友的ip 和他机子所监听的端口号) 实验过了,没有问题了哈。
你不能写一个别人用不上的端口呀,如果自动监控,用java写太复杂,没必要吧,或是你用c++写一个外部程序,写成文件,让java程序加载吧!