Android客户端 - 服务器通信

时间:2016-07-13 14:02:02

标签: android udp

无法接收从服务器到客户端的消息,即使能够从客户端向服务器发送消息,我也必须在大多数时间更改端口号,因为当我运行服务器时,它会给出错误,说“地址已经在使用“但是一旦我更改了端口号,它就可以正常用于客户端服务器。

服务器代码:

 import java.net.*;

    class UDPServer
    {
        public static void main(String args[]) throws Exception
            {
                DatagramSocket serverSocket = new DatagramSocket(7683);

                    byte[] receiveData = new byte[1024];
                    byte[] sendData= new byte[1024];

                    while(true)
                        {
                            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                            serverSocket.receive(receivePacket);
                            String sentence = new String(receivePacket.getData());
                            System.out.println("RECEIVED:" + sentence);
                            InetAddress IPAddress = receivePacket.getAddress();
                            int port = receivePacket.getPort();
                            String capitalizedSentence = sentence.toUpperCase();
                            sendData = capitalizedSentence.getBytes();
                            DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, port);
                            serverSocket.send(sendPacket);
                            //serverSocket.close();
                        }
            }
    }

客户代码:

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
                DatagramSocket clientSocket = new DatagramSocket();
                InetAddress IPAddress = InetAddress.getByName("000.00.0.000");
                byte[] sendData = new byte [1024];
                byte[] receiveData = new byte [1024];
//                String sentence = inFromUser.readLine();
                String sentence = "Hello";
                sendData = sentence.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7683);
                clientSocket.send(sendPacket);
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                clientSocket.receive(receivePacket);
                String modifiedSentence = new String(receivePacket.getData());
                System.out.println("FROM SERVER:" + sentence);
                clientSocket.close();

0 个答案:

没有答案