java - 创建 Java DatagramSocket 对象时为 "address already in use cannot bind"。

标签 java port datagram

我通过 MyDatagramSocket 向 DatagramSocket 的构造函数传递一个整数,但收到错误:“地址已在使用中:无法绑定(bind)”。我从 NetBeans 运行客户端,从终端运行服务器。我尝试了几个不同的端口,重新启动 Netbeans - 关闭终端,甚至尝试重新启动计算机。

我尝试使用 netstat 查找端口,但我什至没有在那里找到它。这是我的代码:

客户端.java

package datagramcounterserver;
import java.io.*;

public class Client {
    public static void main(String[] args) {
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(is); 
        try {
            System.out.println("Welcome to the Daytime client. \n" + "What is the name of the server host?"); 
            String hostName = br.readLine(); 
            if (hostName.length() == 0) 
                hostName = "localhost"; 
            System.out.println("What is the port number of the server host?"); 
            String portNum = br.readLine(); 
            if (portNum.length() == 0) {
                portNum = "223";
            }
            System.out.println("Counter receiver from the server: " + Helper.getCounter(hostName, portNum));
        }
        catch(Exception ex) {
            ex.printStackTrace(); 
        }
    }
}

Helper.java

package datagramcounterserver;
import java.net.*; 
import java.net.InetAddress;

public class Helper {
    public static int getCounter(String hostName, String portNum) {
        int counter = 0; 
        String message = "1"; 
        try {
            InetAddress serverHost = InetAddress.getByName(hostName);
            int serverPort = Integer.parseInt(portNum);
            MyDatagramSocket mySocket = new MyDatagramSocket(serverPort);
            mySocket.sendMessage(serverHost, serverPort, " ");
            message = mySocket.receiveMessage(); 
            System.out.println("Message received: " + message);
            counter = Integer.parseInt(message.trim());
            mySocket.close();
        }
        catch (Exception ex) {
            ex.printStackTrace(); 
        }
        return counter;
    }
}

MyDatagramSocket.java

package datagramcounterserver;

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

public class MyDatagramSocket extends DatagramSocket {
    final int MAX_LEN = 10;
    MyDatagramSocket(int portNo) throws SocketException {
        super(portNo); 
    }

    public void sendMessage(InetAddress receiverHost, int receiverPort, String message) throws IOException {
        byte[] sendBuffer = message.getBytes();
        DatagramPacket datagram = new DatagramPacket(sendBuffer, sendBuffer.length, receiverHost, receiverPort);
        this.send(datagram);
    }

    public String receiveMessage() throws IOException {
        byte[] receiveBuffer = new byte[MAX_LEN]; 
        DatagramPacket datagram = new DatagramPacket(receiveBuffer, MAX_LEN); 
        this.receive(datagram); 
        String message = new String(receiveBuffer); 
        return message; 
    }
}

MyServerDatagraphSocket.java

package datagramcounterserver;
import java.net.*;
import java.io.*; 

public class MyServerDatagramSocket extends DatagramSocket {
    static final int MAX_LEN = 100; 
    MyServerDatagramSocket(int portNo) throws SocketException {
        super(portNo); 
    }
    public void sendMessage(InetAddress receiverHost, int receiverPort, String message) throws IOException {
        byte[] sendBuffer = message.getBytes(); 
        DatagramPacket datagram = new DatagramPacket(sendBuffer, sendBuffer.length, receiverHost, receiverPort); 
        this.send(datagram); 
    }
    public String receiveMessage() throws IOException {
        byte[] receiveBuffer = new byte[MAX_LEN];
        DatagramPacket datagram = new DatagramPacket(receiveBuffer, MAX_LEN); 
        this.receive(datagram); 
        String message = new String(receiveBuffer);
        return message; 
    }
    public DatagramMessage receiveMessageAndSender() throws IOException {
        byte[] receiveBuffer = new byte[MAX_LEN];
        DatagramPacket datagram = new DatagramPacket(receiveBuffer, MAX_LEN);
        this.receive(datagram); 

        DatagramMessage returnVal = new DatagramMessage(); 
        returnVal.putVal(new String(receiveBuffer), datagram.getAddress(), datagram.getPort());
        return returnVal; 
    }
}

服务器.java

package datagramcounterserver;
import java.io.*; 

public class Server {

    static int counter = 0; 
    public static void main(String[] args) {
        int serverPort = 223;
        if (args.length == 1)
            serverPort = Integer.parseInt(args[0]);
        try {
            MyServerDatagramSocket mySocket = new MyServerDatagramSocket(serverPort);
            System.out.println("Counter server ready.");
            while (true) {
                DatagramMessage request = mySocket.receiveMessageAndSender();
                System.out.println("Request received");
                increment(); 
                System.out.println("counter sent "+ counter);
                mySocket.sendMessage(request.getAddress(), request.getPort(), String.valueOf(counter)); 
            }
        }
        catch (Exception ex) {
                ex.printStackTrace(); 
        }
    }

    static private synchronized void increment() {
        counter++; 
    }

}

最佳答案

您的服务器和客户端都绑定(bind)到该端口,但要启动的第二个服务器无法绑定(bind)。采用单个 int 参数的 DatagramSocket 构造函数相当于创建 DatagramSocket 并调用 socket.bind(port)

虽然这是您希望在服务器上出现的行为,但在客户端上您不希望绑定(bind)到端口 - 您希望连接到服务器。这是通过使用 connect() 方法来完成的。您可能想将 MyDatagramSocket 类的构造函数更改为如下所示:

MyDatagramSocket(String address, int portNo) throws SocketException {
    super(); 
    connect(InetAddress.getByName(address), portNo);
}

关于java - 创建 Java DatagramSocket 对象时为 "address already in use cannot bind"。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42895657/

相关文章:

java - 这个说法在java中正确吗?

java - 使用 UDP 数据包以位特定顺序发送电话号码 Java

java - 我应该包含什么 jar 在基于 hibernate 的应用程序中使用 javax.persistence 包?

Linux命令使端口监听

Java:检查哪些进程绑定(bind)到端口?

Apache 服务器 : no listening sockets available

java - Java中的树遍历: Iterative or recursive?

java - 为什么 rs.next() 不转到另一条记录

java - 处理视频库在 Linux (Ubuntu 13.04) 上不起作用

java - 如何管理打开的数据报套接字以避免超过最大值?