一:引言
实现一方 到另一方可以发送信息,而另一方也能回复信息。这里用到了多线程,开辟两条不同的执行路径,一个执行接收信息,一个执行发送信息,但其端口号 要对应 ,即一个发送端口,对应一个接收端口。
二:上码:
1:发送端类的实现
package com.wyj.three;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class Demo12_talk发送02 implements Runnable{
private DatagramSocket client;
private BufferedReader reader;
private int port;
private int toport;
private String toIP;
public Demo12_talk发送02(int port,int toport,String toIP) {
this.port = port;
this.toport = toport;
this.toIP = toIP;
try {
client = new DatagramSocket(port);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while( true ) {
String msg ;
try {
msg = reader.readLine();
byte[] dates = msg.getBytes();
DatagramPacket packet = new DatagramPacket(dates, 0,dates.length,
new InetSocketAddress(this.toIP,this.toport));
client.send(packet);
if(msg.equals("bye")) {
break;
}
}catch( IOException e ) {
e.printStackTrace();
}
}
client.close();
}
}
2:接受端类的实现
package com.wyj.three;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Demo11_talk接收端02 implements Runnable{
DatagramSocket server;
public Demo11_talk接收端02(int port) {
try {
server = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
byte [] container = new byte[1024*60];
DatagramPacket packet = new DatagramPacket(container,container.length);
try {
server.receive(packet);
byte[] dates = packet.getData();
int len = packet.getLength();
String date = new String(dates,0,len);
System.out.println(date);
if( date.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
server.close();
}
}
3:具体的实现(老师与学生的交流)
package com.wyj.three;
public class Demo1_student {
public static void main(String[] args) {
new Thread(new Demo11_talk接收端02(9998)).start();
new Thread(new Demo12_talk发送02(5555, 9997, "localhost")).start();
}
}
4:具体的实现(老师与学生的交流)
package com.wyj.three;
public class Demo2_teacher {
public static void main(String[] args) {
new Thread(new Demo12_talk发送02(8888, 9998, "localhost")).start();
new Thread(new Demo11_talk接收端02(9997)).start();
}
}
不同的颜色代表接受端和发送端不相同(黑色代表接收端)
|