2025-02-09

        執行時,服務端使用java test 1啟動,客戶端使用java test啟動,當服務器端鍵入字符時,客戶端也會打印出相應的字符,希望下面的代碼對你有所收獲。

  1. import java.net.*;
  2. public class test {
  3.     public static int serverPort = 666;
  4.     public static int clientPort = 999;
  5.     public static int buffer_size = 1024;
  6.     public static DatagramSocket ds;
  7.     public static byte buffer[]=new byte[buffer_size];
  8.     public static void TheServer() throws Exception {
  9.         int pos=0;
  10.         while(true){
  11.             int c = System.in.read();
  12.             switch(c){
  13.             case :
  14.                 ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
  15.                 pos = 0;
  16.                 break;
  17.             default :
  18.                 buffer[pos ]=(byte)c;
  19.             }
  20.         }
  21.     }
  22.     public static void TheClient() throws Exception{
  23.         while(true){
  24.             DatagramPacket p = new DatagramPacket(buffer,buffer.length);
  25.             ds.receive(p);
  26.             System.out.println(new String(p.getData(),0,p.getLength()));
  27.         }
  28.     }
  29.     public static void main(String[] args) throws Exception{
  30.         // TODO Auto-generated method stub
  31.         if(args.length==1){
  32.             ds = new DatagramSocket(serverPort);
  33.             TheServer();
  34.         }else{
  35.             ds = new DatagramSocket(clientPort);
  36.             TheClient();
  37.         }
  38.     }
  39. }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *