**
两人进行聊天、咨询
**
服务端接收消息, 代码如下:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* 接收端
* 1.Runnable接口建立线程
* 2.DatagramSocket类创建数据包套接字、DatagramPacket类数据拆包
* 3.接收发送端的消息数据包--拆包后输出消息内容--以“bye”结束断开连接
* 4.注意捕获异常
*/
public class TalkRecive1 implements Runnable { //服务端
DatagramSocket socket = null;
private int myPort; //接收端的端口
private String msgForm; //发送者的名称
public TalkRecive1(int myPort,String msgForm) {
this.myPort = myPort;
this.msgForm = msgForm;
try {
socket = new DatagramSocket(myPort);
}catch (SocketException e)
{
e.printStackTrace();
}
}
@Override
public void run() {
while (true)
{
try{
//准备接收包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
//阻塞式接收包裹
socket.receive(packet);
//断开连接
byte[] data = packet.getData();
String reciveData = new String(data,0, data.length);
System.out.println(msgForm + " : " + reciveData);
//接收到“bye”结束聊天
if(reciveData.equals("bye"))
{
break;
}
}catch (IOException E)
{
E.printStackTrace();
}
}
socket.close();//关闭
}
}
客户端发送消息, 代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
* 采用UDP通信模式实现多人聊天:
* */
/**
* 发送端
* 1.Runnable接口建立线程;
* 2.DatagramSocket类创建数据包套接字、DatagramPacket类数据打包
* BufferedReader类创建缓冲字符输入流、InputStreamReader类读取字节将其解码为字符
* 3.从控制台输入聊天内容:接收聊天内容 —— 将字符串转化为字节打包发出--以“bye”结束发送消息断开连接
* 4.注意捕获异常
*
*/
public class TalkSend1 implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;
private int myPort; //发送者的端口号
private String toIP; //接收者的IP
private int toPort; //接收者的端口号
//构造方法
public TalkSend1(int myPort, String toIP, int toPort) {
this.myPort = myPort;
this.toIP = toIP;
this.toPort = toPort;
try{
socket = new DatagramSocket(myPort);
reader = new BufferedReader(new InputStreamReader(System.in)); //准备数据 :控制台读取数据
}catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void run() {
while (true)
{
try{
System.out.println("WantSendmsg:");
String data = reader.readLine();//接收控制台输入的一行;
byte[] datas = data.getBytes(); //getBytes()是将一个字符串转化为一个字节数组
//将数据打包发出
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
//将包发出
socket.send(packet);
if (data.equals("bye")) //收到"bye"后聊天结束
{
break;
}
}catch (Exception e)
{
e.printStackTrace();
}
}
//关闭
socket.close();
}
}
模拟聊天, 分别建立两个线程,调用服务端和客户端进行消息的发送与接收。俩个线程代码如下:
//Frank
public class TalkPerson1 {
public static void main(String[] args) {
new Thread(new TalkSend1(1111,"localhost",8888)).start();
new Thread(new TalkRecive1(7777,"Mary")).start();
}
}
//分开两个class文件
//Mary
public class TalkPerson2 {
public static void main(String[] args) {
new Thread(new TalkSend1(1001,"localhost",7777)).start();
new Thread(new TalkRecive1(8888,"Frank")).start();
}
}
两个人的执行界面如下: