Using the UDP protocol, write a chat software that can send messages and display messages in the same interface.
The code is implemented as follows:
Package com.abel.socket;
Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import Java.util.Scanner;
/*
* Multi-threaded in one interface to complete the sending and receiving
* 1 Sending Send
* * * * Create datagramsocket, random port number
* Create Datagrampacket, specify data, length, address, port
* Send Datagrampacket using Datagramsocket
* Close Datagramsocket
Accept Receive
* Create Datagramsocket, specify port number
* Create Datagrampacket, specify byte array length
* Receive Datagrampacket using Datagramsocket
* Close Datagramsocket
* Get data from Datagrampacket
*/
public class Demo3_morethread {
public static void Main (string[] args) throws Interruptedexception {
New Receive (). Start ();
Thread.Sleep (10);
New Send (). Start ();
}
}
Class Receive extends thread{
public void Run () {
try {
Datagramsocket socket= New Datagramsocket (3321);
while (true) {
Datagrampacket packet=new Datagrampacket (new byte[1024], 1024);
Socket.receive (packet);
Byte[]arr=packet.getdata ();
int Len=packet.getlength ();
String ip=packet.getaddress (). gethostaddress ();//Get IP Address
int Port=packet.getport ();//Get Port number
System.out.println (ip+ ":" +port+ ":" +new String (Arr,0,len));
}
}
catch (IOException e) {
E.printstacktrace ();
}
}
}
Class Send extends thread{
public void Run () {
try {
Scanner sc=new Scanner (system.in);
Datagramsocket socket=new Datagramsocket ();
while (true) {
String Str=sc.nextline ();
if ("Quit". Equals (str)) {
Break
}
Datagrampacket packet=new Datagrampacket (Str.getbytes (), str.getbytes (). Length, Inetaddress.getbyname ("127.0.0.1") , 3321);
Socket.send (packet);
}
Socket.close ();
}
catch (IOException e) {
E.printstacktrace ();
}
}
}
Java Network programming communication based on UDP protocol