首页 > 其他 > 详细

聊天Demo

时间:2016-02-05 00:57:52      阅读:185      评论:0      收藏:0      [点我收藏+]

简单聊天功能,没有界面

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

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();
        }
    }

 

聊天Demo

原文:http://www.cnblogs.com/lovedaydream/p/5182169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!