//创建一个发送聊天的类
package com.simpro.util;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class LTfasong implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
//创建一个发送消息的套接字
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
try {
System.out.println("发送端发送消息");
Scanner sc = new Scanner(System.in);
String msg = sc.next();
byte [] bytes = msg.getBytes();//发送的内容转化为字节数组
InetAddress ip = InetAddress.getByName("192.168.94.1");//接受内容的Ip地址
//创建要发送的数据包,然后用套接字发送
DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,ip,8080);
//用套接字发送数据包
sendSocket.send(datagramPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
LTfasong s = new LTfasong();
Thread thread = new Thread(s);
thread.start();
LTjieshou r = new LTjieshou();
Thread thread1 = new Thread(r);
thread1.start();
}
}
//创建一个接受聊天信息的类
package com.simpro.util;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class LTjieshou implements Runnable {
@Override
public void run() {
System.out.println("接收端");
//创建接受消息的套接字
DatagramSocket receviceSocket = null;
try {
receviceSocket = new DatagramSocket(8080);
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
try {
byte [] bytes = new byte[2048];
//创建一个数据包来接受消息
DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);
//用套接字接受数据包
receviceSocket.receive(datagramPacket);
//得到发送端的ip地址对象
InetAddress ip = datagramPacket.getAddress();
//将接受到的消息转换为字符串
String rec = new String(datagramPacket.getData()) ;
System.out.println(ip.getHostAddress()+"发送的消息为:"+rec);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
LTjieshou r = new LTjieshou();
Thread thread = new Thread(r);
thread.start();
}
}
//ok,结束了,就是这么简单,本Demo仅给大家一个思路,具体根据自己项目实际情况去修改使用。
//注意事项:发送端的端口要和接收端的端口保持一致。
效果图给大家看一下!!!