六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 100|回复: 0

Datagrams 数据报 示例

[复制链接]

升级  57%

113

主题

113

主题

113

主题

举人

Rank: 3Rank: 3

积分
371
 楼主| 发表于 2013-2-5 01:41:10 | 显示全部楼层 |阅读模式
//Demonstrate Datagrams.
import java.net.*;
class WriteServer{
 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 -1:
     System.out.println("Server Quits.");
     return;
    case '\r':
     break;
    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{
  if(args.length == 1){
   ds = new DatagramSocket(serverPort);
   TheServer();
  }else{
   ds = new DatagramSocket(clientPort);
   TheClient();
  }
 }
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表