文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>java-数据报

java-数据报

时间:2010-07-27  来源:cj_gameboy

import java.net.*;

public class test {
    public static int serverPort = 666;
    public static int clientPort = 999;
    public static int buffer_size = 1024;
    public static DatagramSocket ds;
    public static byte buffer[]=new byte[buffer_size];
    public static void TheServer() throws Exception {
        int pos=0;
        while(true){
            int c = System.in.read();
            switch(c){
            case '\n' :
                ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
                pos = 0;
                break;
            default :
                buffer[pos++]=(byte)c;
            }
        }
    }
    public static void TheClient() throws Exception{
        while(true){
            DatagramPacket p = new DatagramPacket(buffer,buffer.length);
            ds.receive(p);
            System.out.println(new String(p.getData(),0,p.getLength()));
        }
    }
    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub

        if(args.length==1){
            ds = new DatagramSocket(serverPort);
            TheServer();
        }else{
            ds = new DatagramSocket(clientPort);
            TheClient();
        }
    }
    
}


执行时,服务端使用java test 1启动,客户端使用java test启动,当服务器端键入字符时,客户端也会打印出相应的字符。
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载