執行時,服務端使用java test 1啟動,客戶端使用java test啟動,當服務器端鍵入字符時,客戶端也會打印出相應的字符,希望下面的代碼對你有所收獲。
- 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 :
- 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();
- }
- }
- }