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).