【Java】学习路径55-练习:制作一个聊天室(多线程、UDP、双向传输数据)
2024-09-06 17:48:40
创建四个类,实现双向聊天的功能。
接收线程:
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:
最新文章
- python 学习第二天
- Linux+Mono+WebService:CS1703: An assembly with the same identity--mscorlib
- iOS之App加急审核详细步骤
- CentOS 7 下的LAMP实现以及基于https的虚拟主机
- MySQL 常见的sql命令
- cygwin-使用介绍
- 比较核心的技术了 虚拟ip的一种实现方式(手工添加和C#添加)
- [POJ1050]To the Max
- win10远程桌面连接
- SQL Server 之 DBCC
- poj2686-Traveling by Stagecoach(状压dp)
- android学习日记19--四大组件之BroadcastReciver(广播接收者)
- 归纳决策树ID3(Java实现)
- iOS IAP教程
- Android最佳性能实践(四)——布局优化技巧
- (一〇六)iPad开发之UIPopoverController的使用
- Python matplotlib绘图学习笔记
- .net core 2.0 配置Session
- android4.4之后的HttpUrlConnection的实现是基于okhttp
- FortiGate安全策略说明