创建四个类,实现双向聊天的功能。

接收线程:

import java.io.IOException;
import java.net.*; public class ReceiveThread implements Runnable{
private int port;
public ReceiveThread (int port){
this.port=port;
}
@Override
public void run() {
DatagramSocket ds = null;//如果要监听,则在构造的时候就要指定需要监听的端口。
try {
ds = new DatagramSocket(port);
while(true){
byte[] buf = new byte[1024];
int length = buf.length;
DatagramPacket dp = new DatagramPacket(buf,length);
try {
ds.receive(dp);
} catch (IOException e) {
e.printStackTrace();
} String str = new String(dp.getData(),0,dp.getLength());
InetAddress ip = dp.getAddress(); System.out.println("来自:"+dp.getSocketAddress()+"的信息\n"+str+"\n-----------");
}
} catch (SocketException e) {
e.printStackTrace();
}finally {
ds.close();
}
}
}

发送线程:

import java.io.IOException;
import java.net.*;
import java.util.Scanner; public class SendThread implements Runnable{
private int port;
public SendThread (int port){
this.port=port;
}
@Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
Scanner sc = new Scanner(System.in); while(true){
// byte[] buf = "我是王二萌remoo,你也可以叫我remoo".getBytes();
String str = sc.next();
if(str.equals("end"))break;
byte[] buf = str.getBytes();
int length = buf.length;
InetAddress ip = null;
try {
ip = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
e.printStackTrace();
} DatagramPacket dp = new DatagramPacket(buf,length,ip,port);
try {
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
}
ds.close(); } catch (SocketException e) {
e.printStackTrace();
}
}
}

用户1:

public class Chat_User01 {
public static void main(String[] args) { //用户1的接收端线程启动
ReceiveThread rt = new ReceiveThread(8898);
new Thread(rt).start(); //用户1的发送端口线程
SendThread st = new SendThread(8899);
new Thread(st).start(); }
}

用户2:

public class Chat_User02 {
public static void main(String[] args) {
//用户2的接收端线程启动
ReceiveThread rt = new ReceiveThread(8899);
new Thread(rt).start();
//用户1的发送端口线程
SendThread st = new SendThread(8898);
new Thread(st).start();
}
}

然后启动用户1、用户2:

最新文章

  1. python 学习第二天
  2. Linux+Mono+WebService:CS1703: An assembly with the same identity--mscorlib
  3. iOS之App加急审核详细步骤
  4. CentOS 7 下的LAMP实现以及基于https的虚拟主机
  5. MySQL 常见的sql命令
  6. cygwin-使用介绍
  7. 比较核心的技术了 虚拟ip的一种实现方式(手工添加和C#添加)
  8. [POJ1050]To the Max
  9. win10远程桌面连接
  10. SQL Server 之 DBCC
  11. poj2686-Traveling by Stagecoach(状压dp)
  12. android学习日记19--四大组件之BroadcastReciver(广播接收者)
  13. 归纳决策树ID3(Java实现)
  14. iOS IAP教程
  15. Android最佳性能实践(四)——布局优化技巧
  16. (一〇六)iPad开发之UIPopoverController的使用
  17. Python matplotlib绘图学习笔记
  18. .net core 2.0 配置Session
  19. android4.4之后的HttpUrlConnection的实现是基于okhttp
  20. FortiGate安全策略说明

热门文章

  1. 批处理(bat、cmd)命令总结
  2. 重学ES系列之拓展运算符
  3. 重学ES系列之新型数据结构Map应用
  4. 关于全栈项目【臻美Chat】https访问 遇到的问题【技术栈:Nodejs】
  5. Python Excel 操作
  6. PTA(BasicLevel)-1018 锤子剪刀布
  7. Eclipse拷贝动态的web工程
  8. 记录自己NVIDIA GeForce MX250迷之安装cuda+pytorch成功了
  9. SpringBoot之MongoDB附件操作
  10. 使用vs2022编译assimp,并基于OpenGL加载模型