了解UDP;
UDP是一种支持一个无连接的传输协议,除了给应用程序发送数据包功能并允许它们在所需的层次上架构自己的协议之外,几乎没有做什么特别的事情。面向连接的是 TCP,该协议几乎做了所有的事情。
实现一台主机上实现两个机器聊天,需要用到多线程,
发送端
package tiantisai;
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 UDPSender implements Runnable{
DatagramSocket datagramSocket = null;
BufferedReader bufferedReader = null;
// 需要一个自己的一个端口号,对方的IP,对方的端口号
private int formHost;
private String toIP;
private int toHost;
public UDPSender(int formHost, String toIP, int toHost) {
this.formHost = formHost;
this.toIP = toIP;
this.toHost = toHost;
try {
datagramSocket = new DatagramSocket(formHost);
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
String data = null;
try {
data = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = data.getBytes();
//打包发送
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(this.toIP, this.toHost));
try {
datagramSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
//判断出循环
if (data.equals("bye")){
break;
}
//关闭资源
datagramSocket.close();
}
}
}
接受端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPReceive implements Runnable{
DatagramSocket socket = null;
// 接受的端口号
private int receiveHost;
//设置名字
private String name;
public UDPReceive(int receiveHost, String name) {
this.receiveHost = receiveHost;
this.name = name;
try {
socket = new DatagramSocket(receiveHost);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
byte[] bytes = new byte[1024];
//使用DatagramPacket接受发过来的信息,第一个参数需要bytes字节数组,第二个参数表示开始位置,第三个表示结束位置
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
String s = new String(packet.getData(), 0, packet.getLength());
System.out.println(this.name+":"+s);
//判断结束
if (s.equals("bys")){
break;
}
}
//关闭流
socket.close();
}
}
使用多线程模仿
学生端
public class TestStudent {
public static void main(String[] args) {
new Thread(new UDPSender(5555,"localhost",9999)).start();
//接受端
new Thread(new UDPReceive(8888,"老师")).start();
}
}
老师端
public class TestTeacher{
public static void main(String[] args) {
new Thread(new UDPSender(1233,"localhost",8888)).start();
new Thread(new UDPReceive(9999,"学生")).start();
}
}
效果图
由于idea控制台没法分开,所以就只能两个输出站在一个控制台