10黑马币
import java.net.*;
import java.io.*;
class UdpSend2
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=bufr.readLine())!=null)
{
if("886".equals(line))
break;
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("122.244.162.113"),10002);
ds.send(dp);
}
ds.close();
}
}
class UdpRece2
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(10002);
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);
}
}
}
代码是毕老师那资料上拷来的 只改了ip地址 可是端口就是有问题 也不知道是什么问题 应该是我自己电脑上的问题 就是不知道哪要改
|
最佳答案
查看完整内容
是在本机弄接收和发送的吗?
首先
class UdpSend2
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();//这里建立UDP的Socket服务时,需要确定一个用于发送的端口号,你接收的端口号是10002,这里改成10000应该是没问题的,只要不是10002就不会冲突
其次如果还不能解决问题:
把发送和接收的类实现Runnable接口,然后用多线程试试。
改过 ...
|