UDP server,client 代码

服务器端

/**
 * Created with IntelliJ IDEA.
 * User: ipqhjjybj Caroline Jacky
 * Date: 13-12-24
 * Time: afternoon 11:13
 * @description UDP MathServer Example Program
 */
import java.io.*;
import java.net.*;

/** Server which waits for packets from clients.
 **  When a packet is received the server reads a string from the packet payload.
 **  The serevr then writes a packet containing a message consisting of Hello followed by
 **  the String sent by the client to the server.
 **/
public class MathServer {

    //Programs main entry point
    public static void main(String[] args){

        try{
            //Create a DatagramSocket to communicate with the clients
            DatagramSocket serverSocket = new DatagramSocket(10000);

            while(true){
                //Block and wait for incoming packets from clients
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);

                //Read the message from a received packet
                String data = new String( receivePacket.getData());

                //Get the IP address of the machine and the port the packet came from
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();

                //execuption the result
                String newData = data.toUpperCase();
                String response  = "error we don't know ";
                if(newData.contains("ADD")){
                   String newString =  newData.substring(newData.indexOf("ADD")+3);
                   int i = 0;
                   for(;i < newString.length();i++){
                       if((newString.charAt(i) <= '9' && newString.charAt(i) >= '0') ||
                               (newString.charAt(i) == '-'&&
                                       (newString.charAt(i+1) <= '9'
                                               && newString.charAt(i+1) >= '0'))){
                           break;
                       }
                   }
                   if(i >= newString.length()){
                       response = "error : don't contain numbers";
                   }else{
                       String resultStr[] = newString.split("_");

                       int result = 0;
                       try{
                           int length = resultStr.length;
                           for(int j = 0;j < length-1;j++)
                           {
                              if(!resultStr[j].equals("")){
                                int newInt = Integer.parseInt(String.valueOf(resultStr[j]));
                                result += newInt;
                              }
                           }

                           response = String.valueOf(result);
                       }catch(NumberFormatException e){
                           response = "NumberFormatError " + e.toString() + " and can not contain letters or other illegal character";
                       }
                   }
                }else{
                   response = "error : don't contain add!";
                }
                //return the execution of the result
                //Construct a new message to send back
                byte[] sendData = response.getBytes();

                //Construct and send the packet contaning a response to the client
                DatagramPacket sendPacket =  new DatagramPacket(sendData, sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);
            }
        }catch(Exception e){
            System.out.println(e.toString());
        }


    }
}


客户端:

/**
 * Created with IntelliJ IDEA.
 * User: ipqhjjybj Caroline Jacky
 * Date: 13-12-24
 * Time: morning 11:11
 * @description UDP MathClient Example Program
 */

import java.io.*;
import java.net.*;

/**
 * A UDP Client Program which reads a String from the command line
 * connects to a server program running on the same machine
 * and sends it the String argument in a UDP packet.
 * It then reads a response from
 * the server and displays it to the user.
 **/
public class MathClient {

    //Main entry point for program
    public static void main(String[] args){

        //Check that we have the right number of arguments.
        if(args.length < 3){
            //Display usage information
            displayUsage();
            System.exit(0);
        }

        try{
            //Create a DatagramSocket to communicate with the server
            DatagramSocket clientSocket = new DatagramSocket();

            //Get the IP Address of the server
            InetAddress IPAddress = InetAddress.getByName("localhost");

            //Send a UDP packet containing the commeand line argument to the server
            //To connect all arguments to deliver a newline
            String newLine="_";
            for(int i = 0;i < args.length;i++)
            {
                newLine = newLine + args[i] + "_";
            }
            byte[] sendData = newLine.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 10000);
            clientSocket.send(sendPacket);

            //Read a UDP packet from the server
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);
            //Display the data returned by the server
            String response = new String(receivePacket.getData());
            System.out.println(response);

            //Close the connection to the server
            clientSocket.close();
        }catch(Exception e){
            System.out.println(e.toString());
        }
    }

    //Method to display usage information to the user
    public static void displayUsage(){
        System.out.println("Usage: Please at the least input three arguments : Add 3 4");
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值