码迷,mamicode.com
首页 > 其他好文 > 详细

UDP模式聊天

时间:2016-08-15 14:27:08      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

//client (前台)

 

 

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class Client {
    
    //UDP聊天
    public static void main(String[] args) throws Exception {
        //创建字符串
        String word ="Hello";
        //将字符串转化成字节
        byte[] bytes = word.getBytes();
        DatagramSocket socket =new DatagramSocket();
        DatagramPacket packet =new DatagramPacket(bytes, 0,bytes.length,InetAddress.getByName("localhost"),50000);
        socket.send(packet);
    }

}

//server (后台)

 

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class Server {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("开启后台");
        //接受或发送数据报的套结字
        DatagramSocket socket =new DatagramSocket(50000);
        byte [] bytes =new byte[1024];
        //表是存放数据的数据表
        DatagramPacket packet =new DatagramPacket(bytes, 0,bytes.length);
        socket.receive(packet);
        byte[] data = packet.getData();
        String temp =new String(data,0,data.length);
        System.out.println(temp);
    }

}

 

UDP模式聊天

标签:

原文地址:http://www.cnblogs.com/myhome-1/p/5772649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!