通过socket和Udp协议简单实现一个群体聊天工具(控制台)
2024-09-07 05:07:01
编写一个聊天程序。
有收数据的部分 和 发数据的部分。
这两个部分需要同时执行,
这就用到多线程技术,
一个线程负责收,一个现象负责发。
因为收和发动作是不一致的,所以要定义两个run方法
而且这两个方法要封装到不同类中。
import java.net.*;
import java.io.*;
发送端:
class Send implements Runnable
{
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
BufferedReader bufr=
new BufferedReader(new InputStreamReader(System.in));
String line=null; while((line=bufr.readLine())!=null)
{
if ("886".equals(line))
break; byte[] buf=line.getBytes(); DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.102"),10002);
//DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10002); ds.send(dp);
} }
catch (Exception e)
{
throw new RuntimeException("发送失败");
}
}
}
接收端:
class Receive implements Runnable
{
private DatagramSocket ds;
public Receive(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try
{
//循环接收
while (true)
{
byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf,buf.length); ds.receive(dp); String ip=dp.getAddress().getHostAddress(); String data=new String (dp.getData(),0,dp.getLength()); System.out.println(ip+":"+data); }
}
catch (Exception e)
{
throw new RuntimeException("接收失败");
}
} }
主函数:
class ChatDemo
{
public static void main(String[] args) throws Exception
{
DatagramSocket sendSocket=new DatagramSocket();
DatagramSocket receiveSocket=new DatagramSocket(10002); new Thread(new Send(sendSocket)).start();
new Thread(new Receive(receiveSocket)).start();
}
}
最新文章
- Idea 快捷键
- str.format
- Trumbowyg - 轻量的 WYSIWYG 编辑器
- 【图文详解】scrapy安装与真的快速上手——爬取豆瓣9分榜单
- hdu 1030 Delta-wave (C++, 0ms, explanatory comments.) 分类: hdoj 2015-06-15 12:21 45人阅读 评论(0) 收藏
- ajaxSubmit中option的参数
- selenium python (六)定位一组对象
- MSSQL手札一 MSSQL的游标
- red5下nginx安装配置
- C. Sonya and Queries
- 金山助手流氓软件-被进程sjk_daemon.exe坑死
- JAVA核心技术I---JAVA基础知识(内部类)
- python要点
- 网络通信协议三之TCP/IP模型详解
- StringUtils方法介绍
- wsl(Windows Subsystem for Linux)安装简易指南
- iOS - 获取安装所有App的Bundle ID
- English trip -- VC(情景课)10 B Around the house 在家里
- 01Tensorflow学习之Tensorflow基本介绍
- part1:13-linux编译器GCC