无法为UDP服务器打开端口17

时间:2018-10-01 12:05:38

标签: java udp serversocket

这是服务器和客户端的Java代码。每当我编译以下代码时,都会出现错误You can check the error here。似乎我无法为服务器打开端口17,因为错误消息指出该地址已被使用,然后还会显示nullPointerException 请帮帮我。我快要疯了。

//服务器代码

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

public class Server {

private static DatagramSocket socket;

    public static void main(String[] argv) throws Exception {

        try {
            socket = new DatagramSocket(17);
        }catch(SocketException e) { 
            e.printStackTrace();
        }

        while(true) {
            try {

                byte[] rec = new byte[512];

                DatagramPacket request = new DatagramPacket(rec,rec.length);
                socket.receive(request);

                String RecM = new String(request.getData(),0,request.getLength());
                System.out.println("Got message from client: " + RecM);


                byte[] smsSend = new byte[512];
                String sms = "Server";
                smsSend = sms.getBytes();

                DatagramPacket reply = new DatagramPacket(smsSend,smsSend.length,InetAddress.getLocalHost(),request.getPort());
                socket.send(reply);

            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
}

//客户代码

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

public class Client {

    private static DatagramSocket socket;

    public static void main(String[] args) throws UnknownHostException{

        InetAddress myIP = InetAddress.getLocalHost();
        String mySMS = "This is my" + myIP;

        InetAddress serverAdd = InetAddress.getLocalHost();

        try {
            socket = new DatagramSocket();
        }catch(SocketException e) {
            e.printStackTrace();[enter image description here][1]
        }

        try {
            byte[] bSend = new byte[512];
            bSend = mySMS.getBytes();

            DatagramPacket request = new DatagramPacket(bSend, bSend.length, serverAdd, 17);
            socket.send(request);

            byte[] bReceive = new byte[512];

            DatagramPacket reply = new DatagramPacket(bReceive, bReceive.length);
            socket.receive(reply);
            String str = new String(reply.getData(),0,reply.getLength());
            System.out.println(str);
        }catch(IOException e) {
            e.printStackTrace();
        }   
    }
}   

This is the error message I got when compiling the server's code

0 个答案:

没有答案