java udp 无法通信
最近学习JAVA socket,自己写了一个非常简单的小例子,但是不知道为什么无法实现通信,自己想了半天也没想出为啥,麻烦大家看下
非常简单的小例子,一端向另外一端写,另外一端收到后写回
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TestUDPSocketServer {
private static final int SIZE = 255;
/**
* UDP服务的服务端
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
byte[] receivedPacket = new byte[SIZE];
DatagramSocket ds = new DatagramSocket();
DatagramPacket dp = new DatagramPacket(receivedPacket,SIZE); //接收的报文
while(true)
{
ds.receive(dp); //接收报文 只接受SIZE大小的,这个方法是阻塞的,
System.out.println("收到 请求啦!!!");
System.out.println("收到的请求数据 --" + new String(dp.getData()));
System.out.println("对方的地址 " +dp.getAddress().getHostAddress()+ "端口 " + dp.getPort());
System.out.println("对方的地址2 " +ds.getInetAddress().getHostAddress()+ "端口 " + ds.getPort());
ds.send(dp); //
dp.setLength(SIZE);
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class TestUDPSocketClient {
private static final int port = 8988;
private static final String content = "HELLO UDP";
private static final int MAX_TRY = 4;
private static final int TIME_OUT = 3000; //3秒超时
private static final String HOST = "127.0.0.1";
public static void main(String[] args) throws IOException
{
InetSocketAddress socketAddress = new InetSocketAddress(HOST,port);
//DatagramSocket client = new DatagramSocket(port,serverAddress); //发送的
DatagramSocket client = new DatagramSocket(); //这里什么都不指定
client.setSoTimeout(TIME_OUT);
DatagramPacket sendpacket =
new DatagramPacket(content.getBytes(),content.getBytes().length,socketAddress); //这里表示这个包发送到serverAddress的port接口
DatagramPacket receivePact =
new DatagramPacket(new byte[content.getBytes().length],content.getBytes().length); //这个包是用来接收数据的
int tries = 0 ; //尝试的次数
boolean receiveResponse = false;
do
{
//当没有收到响应并且 当前尝试次数小于最大尝试次数
client.send(sendpacket); //发出去 ,这个不是阻塞方法
try
{
client.receive(receivePact);
receiveResponse = true ;
}
catch(IOException e)
{
tries ++ ; //尝试次数加一
receiveResponse = false ;
}
}
while(!receiveResponse && tries<MAX_TRY);
if(!receiveResponse)
{
System.out.println("唉, 连不上啦!!!!");
client.close();
return ;
}
//没有抛出异常,收到了服务端返回的数据包
else
{
if(!receivePact.getAddress().equals(socketAddress))
{
//当收到的包不是期望的服务器的
throw new IOException("非法的服务器!");
}
System.out.println("收到服务器发来的报文~!~");
System.out.println("报文内容~"+ new String(receivePact.getData()));
client.close();
}
}
}
BTOBBB
10 years, 8 months ago