Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1063410
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: Java

2010-07-27 16:21:09

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启动,当服务器端键入字符时,客户端也会打印出相应的字符。
阅读(536) | 评论(0) | 转发(0) |
0

上一篇:java-序列化

下一篇:swing-1-Tree与滚动条

给主人留下些什么吧!~~