开发者

How to fix the UDP server in Java?

开发者 https://www.devze.com 2023-04-04 18:02 出处:网络
I had problem to transfer data over TCP. So i was writing a UDP server, but its not working, shows this following error, how can i fix it?

I had problem to transfer data over TCP. So i was writing a UDP server, but its not working, shows this following error, how can i fix it?

My error:

run:
UDP Server started
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:657)
    at socket.UDPHandler.start(UDPHandler.java:25)
    at socket.UDPServer.waitForConnections(UDPServer.java:27)
    at socket.UDPServer.main(UDPServer.java:46)
BUILD STOPPED (total time: 14 seconds)

UDPServer.java

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

public class UDPServer 
{
    private int serverPort = 0;
    private DatagramSocket serverSock = null;
    //private Socket sock = null;

    public UDPServer(int serverPort) throws IOException 
    {
        this.serverPort = serverPort;
        serverSock = new DatagramSocket(serverPort);
        System.out.println("UDP Server started");
    }

    public void waitForConnections() 
    {
        while (true) 
        {
            try {
                //sock = serverSock.accept();
                //System.err.println("Accepted new socket");
                UDPHandler handler = new UDPHandler(serverSock);
                handler.start();
            }
            catch (IOException e){
                e.printStackTrace(System.err);
            }
        }
    }

    public static void main(String argv[]) 
    {
        int port = 8889;

        UDPServer server = null;
        try {
            server = new UDPServer(port);
        }
        catch (IOException e){
            e.printStackTrace(System.err);
        }
        server.waitForConnections();
    }

}

UDPHandler.java

package socket;
import java.io.*;
import java.net.*;
import main.*;
public class UDPHandler implements Runnable 
{
    private DatagramSocket sock = null;
    private DatagramPacket sockInput = null;
    private DatagramPacket sockOutput = null;
    private Thread myThread = null;

    public UDPHandler(DatagramSocket sock) throws IOException 
    {
        this.sock = sock;
        //sockInput = new DatagramPacket();
        //sockOutput = sock.getOutputStream();
        this.myThread = new Thread(this);
    }

    public void start() 
    {
        myThread.start();
    }

    public void run() 
    {
        while(true) 
        {
            byte[] buf=new byte[1024];
            int bytes_read = 0;
            try {                                
                // Incoming - Test                
                sockInput = new DatagramPacket(buf, buf.length);
                sock.receive(sockInput);
                bytes_read = sockInput.getLength();                
                String data = new String(sockInput.getData());
                System.err.println("DATA: " +  bytes_read + " bytes, data=" +data);

                // IP - Test
               开发者_开发问答 InetAddress IPAddress = sockInput.getAddress();
                int port = sockInput.getPort();

                // Sending - Test
                sockOutput = new DatagramPacket(data.getBytes(), data.length(), IPAddress, port);
                sock.send(sockOutput);

            } catch (Exception e) {
                e.printStackTrace(System.err);
                break;
            }
        }

        try {
            System.err.println("Closing socket.");
            sock.close();
        } catch (Exception e) {
            System.err.println("Exception while closing socket, e="+e);
            e.printStackTrace(System.err);
        }

    }

}


You are creating infinite number of threads in while(true) loop in waitForConnection() method. You should call DatagramSocket receive() method within your server (it is blocking operation) and if datagram is received, then delegate its processing to some handler (for example retrieved from thread pool).


I find that the receive() method causes a memory leak. While java waits for UDP packet, my memory usage slowly increases when no other thread is operating. Seems to be increasing memory usage at approx 20kb per hour while running the .receive() method.

Not sure why that would be.


I did not run/debug the code, but the java.lang.OutOfMemoryError makes me think there is something going on inside those while(true) loops, either too many handlers are being created in waitForConnections() (less likely) or too many byte[] buffers are being allocated in run() (more likely).

For the poster, try adding a print statement as the first line of each of those while(true) loops to see how many times they get executed.

It seems odd for the JVM to run out of memory with just a listening UDP server and a simple test application. I hope someone can debug into it and confirm, I can't run the code at the moment.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号