问题描述
- UDP通讯是单向还是双向
-
UDP编程中,为什么服务器不能向客户端发送消息呢,客户端也不能接收服务器发送的消息?
服务器代码:
import java.net.*;public class Server2 {
public static void main(String[] args) { try { //向客户端发送消息 byte[] b="我是服务器".getBytes(); InetAddress ia= InetAddress.getByName("localhost"); DatagramPacket dp=new DatagramPacket(b,b.length,ia,9999); DatagramSocket ds =new DatagramSocket(); ds.send(dp); //接收从客户端发送的数据 byte[] b2=new byte[1024]; DatagramPacket dp2=new DatagramPacket(b2,b2.length); DatagramSocket ds2 =new DatagramSocket(9438); ds2.receive(dp2); //打印客户端发送的数据 System.out.println(new String(b2,0,b2.length)); ds.close(); ds2.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}
客户端代码:
import java.net.*;
public class Client2 {public static void main(String[] args) { try { //向服务器发送数据 byte b[]="我是客户端".getBytes(); InetAddress ia = InetAddress.getByName("localhost"); DatagramPacket dp=new DatagramPacket(b,b.length,ia,9438); DatagramSocket ds=new DatagramSocket(); ds.send(dp); //接收从服务器发送的消息 byte b2[]=new byte [1024]; DatagramPacket dp2=new DatagramPacket(b2,b2.length); DatagramSocket ds2=new DatagramSocket(9999); ds2.receive(dp2); //打印服务器发送的数据 System.out.println("呵呵"); System.out.println(new String(b2,0,b2.length)); ds.close(); ds2.close(); } catch (Exception e) { e.printStackTrace(); } }
}
解决方案
http://blog.csdn.net/zlqqhs/article/details/8759042
参考
解决方案二:
http://blog.csdn.net/zlqqhs/article/details/8759042
参考
解决方案三:
http://blog.csdn.net/zlqqhs/article/details/8759042
参考
时间: 2024-09-24 02:14:31