聊天Demo

it2022-05-05  112

简单聊天功能,没有界面

思路:创建两个线程,分别为接收线程和发送线程,由主函数开启

1、发送

  a、接收soket

  b、建立一个数据包,并将键盘录入的数据封装到数据包内

  c、调用socket的发送函数,将数据包发送给10000端口

2、接收

  a、接收socket

  b、建立接收数据包及缓冲区

  c、调用socke的接收函数,监听1000端口

  b、将接收到的ip地址及信息提取出来

 

 

代码如下:  

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.3.255"),10000); ds.send(dp); } } catch(Exception e){ throw new RuntimeException("fasong"); } } } class Rece implements Runnable { private DatagramSocket ds; public Rece(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().getHostName(); String data = new String(dp.getData(),0,dp.getLength()); System.out.println(ip+": "+data); }} catch(Exception e){ throw new RuntimeException("jieshou"); } } } class ChatDemo { public static void main(String[] args)throws Exception { DatagramSocket sendSocket = new DatagramSocket(); DatagramSocket receSocket = new DatagramSocket(10000); new Thread(new Send(sendSocket)).start(); new Thread(new Rece(receSocket)).start(); } }

 

转载于:https://www.cnblogs.com/lovedaydream/p/5182169.html

相关资源:java实时在线聊天demo

最新回复(0)