The examples in this article share with you the specific code of Java using UDP mode to write chat programs for your reference. The specific content is as follows
Java code:
/* Use UDP mode to write a chat program to send and receive data. One thread receives and one thread sends. Since the sending and receiving actions are inconsistent, two run methods need to be used. These two methods must be encapsulated into different classes. This program ignores some exception handling and does not add UI components. This is a simple sending port 9998 accepting port 9999. It uses a local area network broadcast address, so I also received the message I sent myself [Example]: Simple console chat program*/ import java.net.*; import java.io.*; class Demo { public static void main(String[] args) throws Exception { DatagramSocket sendSocket = new DatagramSocket(9998); //Send DatagramSocket receiveSocket = new DatagramSocket(9999); //Receive new Thread(new MsgSend(sendSocket)).start(); //Send thread new Thread(new MsgRece(receSocket)).start(); //Receive thread} } class MsgSend implements Runnable //Send { private DatagramSocket dsock; public MsgSend(DatagramSocket dsock) { this.dsock= dsock; } public void run() { BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); String lineStr = null; try { while(true) { lineStr = bufr.readLine(); if(lineStr!=null) { if(lineStr.equals("over886")) { break; } else { byte[] dataBuf = lineStr.getBytes(); DatagramPacket dataPack = //Data Packaging new DatagramPacket( dataBuf, dataBuf.length, InetAddress.getByName("192.168.1.255"), //Broadcast 9999 //Target port); dsock.send(dataPack); } } } } bufr.close(); dsock.close(); } catch(Exception e) { throw new RuntimeException("Send failed!"); } } } class MsgRece implements Runnable //Receive { private DatagramSocket dsock; public MsgRece(DatagramSocket dsock) { this.dsock= dsock; } public void run() { try { while(true) { byte[] dataBuf = new byte[1024]; DatagramPacket dataPack = new DatagramPacket(dataBuf,dataBuf.length); dsock.receive(dataPack); //Save the retrieved data to the specified data packet String ip = dataPack.getAddress().getHostAddress(); String data = new String(dataPack.getData(),0,dataPack.getLength()); int port = dataPack.getPort(); System.out.println(); System.out.println("From ip"+ip+" <opposite port>: "+port+" message"); System.out.println(data); } } catch(Exception e) { throw new RuntimeException("Accept failed!"); } finally { dsock.close(); } } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.