//服务器端的监听。。。
//停止按钮jButton2...
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
try{
//isListen = false;
socket.close();
socket = null;
}
catch(Exception e)
{
}
jTextField1.setText("Waiting...");
jButton1.setEnabled(true);
jButton2.setEnabled(false);
}
//开始监听按钮jButton1...
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
try{
//将socket连接到本机的一个可用的端口上
socket = new DatagramSocket(sport);
//System.out.println("Listening on port:" + socket.getLocalPort());
jTextField1.setText("Listening on port: " + socket.getLocalPort());
}
catch(Exception e)
{
//System.out.println("Error: " + e);
//jTextArea1.setText("Error: " + e);
}
//jTextField1.setText(state);
jButton1.setEnabled(false); //.disable();
jButton2.setEnabled(true);
if(socket==null)
return;
//*
while(true)
{
try{
InetAddress address;
int cport;
byte[] buf = new byte[1000];
//接收数据报...到缓冲字节
packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
//输出数据报的内容
String sReceive = new String(packet.getData());
//System.out.println("Received from client: " + sReceive);
//sReceive = "Received from client: " + sReceive;
jTextArea1.append("Received from client: " + sReceive + "\n");
//从数据报获取客户端的源地址和端口
address = packet.getAddress();
cport = packet.getPort();
//发送数据报给客户端以应答...确认接收
String sResponse = "Your packet is received";
sResponse.getBytes(0,sResponse.length(),buf,0);
//生成发送的数据报...到缓冲字节
packet = new DatagramPacket(buf,buf.length,address,cport);
socket.send(packet);
socket.close();
socket = null;
break;
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
//*/
}
//客户端的发送。。。
//发送按钮
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String hostAddress = ""; //服务器端IP地址
int localPort = 0; //本地端口
int hostPort = 0; //服务器端端口
if(jTextField1.getText()==null && jTextField2.getText()==null && jTextField3.getText()==null)
{
System.out.println("input local address & port, server port.");
System.exit(0);
}
else
{
//分别从jTextField123输入信息
hostAddress = jTextField1.getText();
localPort = Integer.parseInt(jTextField2.getText());
hostPort = Integer.parseInt(jTextField3.getText());
}
InetAddress address;
int port;
byte[] buf = new byte[1000];
String sSend = "Hello, Queenie!"; //发给服务器端的文字
try{
socket = new DatagramSocket(localPort); //绑定到本地端口
address = InetAddress.getByName(hostAddress); //从服务器名字获取其IP地址
port = hostPort; //服务器端口
sSend.getBytes(0,sSend.length(),buf,0); //将发送文字放进buf,二进制形式
packet = new DatagramPacket(buf,buf.length,address,port); //绑定buf为数据报
socket.send(packet);
for(int i=0;i<buf.length;i++)
buf[i] = 0;
//接收从服务器端返回的消息
packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
sSend = new String(packet.getData());
//System.out.println("Received from server: " + sSend);
jTextArea1.append("Received from server: " + sSend);
socket.close();
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
问题在于,客户端和服务器端只能发送一次,
因为如果不加蓝色那三句,服务器端就会死循环,停不下来。
我想一直监听,然后客户端发信息,服务器端就显示出来。
谁帮忙解决此问题??
[此贴子已经被作者于2005-12-12 9:44:46编辑过]