使用UDP协议,写一个能在同一界面发送消息,并显示消息的聊天软件。
代码实现如下:
package com.abel.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
/*
* 多线程在一个界面同时完成发送接收
* 1 发送send
* ***创建DatagramSocket,随机端口号
* 创建DatagramPacket,指定数据,长度,地址,端口
* 使用DatagramSocket发送DatagramPacket
* 关闭DatagramSocket
*2 接收 Receive
* 创建DatagramSocket,指定端口号
* 创建DatagramPacket,指定字节数组 长度
* 使用DatagramSocket接收DatagramPacket
* 关闭DatagramSocket
* 从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();//获取ip地址
int port=packet.getPort();//获取端口号
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();
}
}
}