import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
//send线程
public class send implements Runnable
{
DatagramSocket socket = null;
int port;//port that send to
public send(int port) throws Exception { //construcotor in which a socket is
// established
this.port = port;
socket = new DatagramSocket();
}
@Override
public void run()
{
byte[] buffer = new byte[1024]; //to save string
Scanner input = new Scanner(System.in);
while (true)
{
String message = input.nextLine(); //read from console
buffer = message.getBytes(StandardCharsets.UTF_8);//assign the byte array of the string read from console
try {
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port));//creat the packet used to transit to the localhost with correspodning port
socket.send(packet); //send to it
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("sended");
if(message.equals("exit"))
break;
}
socket.close();
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//receive
public class receive implements Runnable
{
DatagramSocket socket = null;
int port;
public receive(int port) throws Exception {
this.port = port;
socket = new DatagramSocket(port);//creat socket used to receive
}
@Override
public void run()
{
byte[] buffer = new byte[1024];
//store the packet data into buffer
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
while (true)
{
try {
socket.receive(packet); //receive from socket to the local packet
} catch (Exception e) {
e.printStackTrace();
}
//utilize the String constructor to converse type
String message = new String(packet.getData(),0,packet.getLength());
System.out.println("received: " + message);
if (message.equals("exit"))
break;
}
socket.close();
}
}
/*
two class to execute the send thread and receive thread
*/
public class Driver1
{
public static void main(String[] args) throws Exception {
new Thread(new receive(6666)).start();
new Thread(new send(6667)).start();
}
}
public class Driver2
{
public static void main(String[] args) throws Exception {
new Thread(new receive(6667)).start();
new Thread(new send(6666)).start();
}
}