编写一个聊天程序。
有收数据的部分 和 发数据的部分。
这两个部分需要同时执行,
这就用到多线程技术,
一个线程负责收,一个现象负责发。

因为收和发动作是不一致的,所以要定义两个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();
}
}

  

最新文章

  1. Idea 快捷键
  2. str.format
  3. Trumbowyg - 轻量的 WYSIWYG 编辑器
  4. 【图文详解】scrapy安装与真的快速上手——爬取豆瓣9分榜单
  5. hdu 1030 Delta-wave (C++, 0ms, explanatory comments.) 分类: hdoj 2015-06-15 12:21 45人阅读 评论(0) 收藏
  6. ajaxSubmit中option的参数
  7. selenium python (六)定位一组对象
  8. MSSQL手札一 MSSQL的游标
  9. red5下nginx安装配置
  10. C. Sonya and Queries
  11. 金山助手流氓软件-被进程sjk_daemon.exe坑死
  12. JAVA核心技术I---JAVA基础知识(内部类)
  13. python要点
  14. 网络通信协议三之TCP/IP模型详解
  15. StringUtils方法介绍
  16. wsl(Windows Subsystem for Linux)安装简易指南
  17. iOS - 获取安装所有App的Bundle ID
  18. English trip -- VC(情景课)10 B Around the house 在家里
  19. 01Tensorflow学习之Tensorflow基本介绍
  20. part1:13-linux编译器GCC

热门文章

  1. cisco 为每个单独的人员设置不同的用户名和密码
  2. SearchView的全面解析
  3. C++类型转换运算符 static_cast,dynamic_cast,reinterpret_cast,const_cast
  4. CentOs上搭建nginx
  5. 安卓手机的后门控制工具SPADE
  6. MongoDB入门学习(1)
  7. vmware下为CentOS7设置静态IP
  8. mongodb 安装及使用
  9. 【WPF学习笔记】之WPF基础:依赖关系属性和通知
  10. subject相关信息