UDP发送消息

server端接收并打印出收到的信息

public static void main(String[] args) throws IOException {//开放端口DatagramSocket socket = new DatagramSocket(9090);//接收数据包byte[] buffer = new byte[1024];DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//阻塞接收socket.receive(packet);//打印发送客户端地址System.out.println(packet.getAddress().getHostAddress());//打印客户端发送的消息System.out.println(new String(packet.getData(),0, packet.getLength()));//关闭连接socket.close();}

客户端发送代码

public static void main(String[] args) throws Exception, UnknownHostException {//1、建立一个SocketDatagramSocket socket = new DatagramSocket();//2、建个包String  msg = "你好呀,服务器";//发送给谁InetAddress localhost = InetAddress.getByName("localhost");int port = 9090;//数据,数据的长度起始,要发送给谁DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);//发送包socket.send(packet);//关闭包socket.close();}

Udp实现聊天

发送端在控制台输入信息发送

public static void main(String[] args) throws Exception {DatagramSocket socket = new DatagramSocket(8888);//准备数据:控制台读取System.inBufferedReader reader = new BufferedReader(new InputStreamReader(System.in));while (true){String data = reader.readLine();byte[] datas = data.getBytes();DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));socket.send(packet);if (data.equals("bye")){break;}}socket.close();}

接收端

public static void main(String[] args) throws Exception {DatagramSocket socket = new DatagramSocket(6666);while (true){//准备接收包裹byte[] container = new byte[1024];DatagramPacket packet = new DatagramPacket(container, 0, container.length);socket.receive(packet);//断开连接 byebyte[] data = packet.getData();String receiveDate = new String(data, 0, data.length);System.out.println(receiveDate);if (receiveDate.equals("bye")){break;}}socket.close();}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部