zoukankan      html  css  js  c++  java
  • 网络编程(UDP协议-聊天程序)

    网络编程中的UDP协议中聊天程序,发送端口,和接受端口。

    发送端口(Send):

    <span style="font-size:18px;">package cn.itcast.net.p3.chat;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    public class Send implements Runnable{
    	private DatagramSocket ds;
    	
    	public Send(DatagramSocket ds){
    		this.ds=ds;
    	}
    	@Override
    	public void run(){
    		try{
    			BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
    		    String line = null;
    		    while((line=bufr.readLine())!=null){
    		    	  byte[] buf = line.getBytes();
    		    	  DatagramPacket dp =
    		    			  new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.3.5"),1001);
    		    ds.send(dp);
    		    if("886".equals(line))
    		    	break;
    		    }
    		}catch(Exception e){
    	}
    		
    	}
    }</span>

    接受端口(Rece):

    <span style="font-size:18px;">package cn.itcast.net.p3.chat;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    
    public class Rece implements Runnable {
    	private DatagramSocket ds;
    	public Rece(DatagramSocket ds){
    		this.ds = ds;
    	}
    	@Override
    	public void run() {
    		try {
    			while(true){
    				//2、创建数据包
    				byte[] buf = new byte[1024];
    				DatagramPacket dp = new DatagramPacket(buf,buf.length);
    				//3、使用接收方法将数据存储到数据包中
    				ds.receive(dp); //阻塞式的
    				//4、通过数据包对象方法,解析其中的数据
    				String ip = dp.getAddress().getHostAddress();
    				int port = dp.getPort();
    				String text = new String(dp.getData(),0,dp.getLength());
    				
    				System.out.println(ip+":"+text);
    				if(text.equals("886")){
    					System.out.println(ip+".....退出聊天室");
    				}
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    		}
    	}
    } </span>


  • 相关阅读:
    Centos 7 运行出错:cannot find a valid basecrl for repo:base/7/x86_64
    nc 使用
    linux uniq去重,awk输出(可用于爆破字典优化)
    关于fixedsys字体 FSEX300.ttf FSEX300-L.ttf FSEX301-L2.ttf
    MyAtoi
    viplugin eclipse
    资源获取即初始化RAII
    阈值分割技术
    图像类型转换
    形态学
  • 原文地址:https://www.cnblogs.com/Rollins/p/4524894.html
Copyright © 2011-2022 走看看