package com.java.demo;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Chat1 {
public static void main(String[] args) throws Exception {
//创建套接字
DatagramSocket socket = new DatagramSocket(1555);
while (true) {
//键盘录入
Scanner sc = new Scanner(System.in);
System.out.println("回复:");
//获取发生的消息
String message = sc.nextLine();
//将消息转换为byte数组
byte[] bytes = message.getBytes();
//创建发生的报包
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 1234);
// DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("10.10.92.127"),1234);
//发送
socket.send(packet);
//接收数据
byte[] bytes1 = new byte[1024];
DatagramPacket packet1 = new DatagramPacket(bytes1, bytes1.length);
socket.receive(packet1);
int port = packet1.getPort();
InetAddress ip = packet1.getAddress();
System.out.println(ip+","+port);
//解析数据
byte[] data = packet1.getData();
//获取接收的有效数据
int len = packet.getLength();
//输出内容
String s = new String(data, 0, len);
System.out.println(s);
if (s.equals("再见")){
socket.close();
break;
}
}
}
}
package com.java.demo;
import javax.sound.sampled.Port;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.util.Scanner;
public class Chat2 {
public static void main(String[] args)throws Exception {
DatagramSocket socket = new DatagramSocket(1234);
while (true) {
//接收数据
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
socket.receive(packet);
int len = packet.getLength();
byte[] data = packet.getData();
//输出
String s = new String(data, 0, len);
System.out.println(s);
//发送
Scanner sc = new Scanner(System.in);
System.out.println("回复:");
String message = sc.nextLine();
byte[] bytes1 = message.getBytes();
int port = packet.getPort();
InetAddress ip = packet.getAddress();
System.out.println(ip+","+port);
DatagramPacket packet1 = new DatagramPacket(bytes1, bytes1.length,ip,port);
socket.send(packet1);
if (s.equals("再见")){
socket.close();
break;
}
}
}
}