java UDP通信问题!
怎么不能实现通信咧???
package com.baidu.www;
import java.net.*;
import java.io.*;
public class UDPClient {
//客户端向服务器端发数据报
public static void main(String[]args)throws Exception{
DatagramSocket ds= new DatagramSocket(8001);//本地端口
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("客户端正在等待键盘输入数据+++");
while(true){
String str=br.readLine();
byte[] bf=str.getBytes();
DatagramPacket dp=new DatagramPacket( bf, bf.length,8000 );
ds.send(dp);
if((str==null)||str.equals("bye"))
break;
}
ds.close();
}
}
package com.baidu.www;
import java.net.*;
public class UDPServer {
public static void main(String[] args)throws Exception {
byte[] bf=new byte[1024];
DatagramSocket ds= new DatagramSocket(8001);
//DatagramPacket dp=new DatagramPacket(bf,bf.length);
System.out.println("服务器端正在等待客户端发送数据+++++");
while(true){
DatagramPacket dp=new DatagramPacket(bf,bf.length);
ds.receive(dp);
String st=new String(dp.getData(),0,dp.getLength());
System.out.println(st);
if((st==null)||st.equals("bye"))
break;
}
ds.close();
}
}
------解决方案--------------------readline中应该加System.in吧
------解决方案--------------------该用这个构造方法,
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。
DatagramPacket dp=new DatagramPacket(bf,bf.length);
改为:
InetAddress address = InetAddress.getByName("127.0.0.1");
DatagramPacket dp=new DatagramPacket(bf,bf.length,address,8001);
------解决方案--------------------
终于给你搞好了
import java.net.*;
import java.io.*;
public class BaiDuUDPClient {
//客户端向服务器端发数据报
public static void main(String[]args)throws Exception{
DatagramSocket ds= new DatagramSocket(8000);//本地端口
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("客户端正在等待键盘输入数据+++");
while(true){
String str=br.readLine();
byte[] bf=str.getBytes();
DatagramPacket dp=new DatagramPacket( bf, bf.length,new InetSocketAddress("127.0.0.1", 8001) );
ds.send(dp);
if((str==null)||str.equals("bye"))
break;
}
ds.close();
}
}
import java.net.*;
public class BaiDuUDPServer {
public static void main(String[] args)throws Exception {
byte[] bf=new byte[1024];
DatagramSocket ds= new DatagramSocket(8001);
//DatagramPacket dp=new DatagramPacket(bf,bf.length);
System.out.println("服务器端正在等待客户端发送数据+++++");
while(true){
DatagramPacket dp=new DatagramPacket(bf,bf.length);
ds.receive(dp);
String st=new String(dp.getData(),0,dp.getLength());
System.out.println(st);
if((st==null)||st.equals("bye"))
break;
}
ds.close();
}
}