java.net.BindException: Address already in use: Cannot bind

Since my other thread flipped out, I’m re-posting this.
Alright, so I’m trying to make a upc client/server and I keep running into this problem no matter where I bind the socket. Maybe someone can tell me what I’m doing wrong?

Note: this is as small as I could make these test cases.

Server:


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class TestServer {
	static DatagramSocket socket;
	public static void main(String[] args){
		int MAX_PLAYERS = 2;
    	int playerNum = 0;
    	
    	boolean listening = true;
        
       
        
        while(listening){
        	byte[] buf = new byte[255];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            System.out.println("Waiting for packet from player: " + playerNum + "\n");
        	
            try {
    			socket = new DatagramSocket(4444);
    		} catch (SocketException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
            
            try {
				socket.receive(packet);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
        	System.out.println("Waiting to connect with player: " + playerNum + "\n");
        	new ClientThread(packet,playerNum).start();
        	//stops here.
        	System.out.println("Connected with player: " + playerNum + " Now incrementing" + "\n");
        	playerNum++;
        	System.out.println("Incremented to: " + playerNum+ "\n");
        }
        
        
        
        //serverSocket.close();
        System.exit(0);
	}
}


Client thread (server)


import java.net.*;
import java.nio.ByteBuffer;

public class ClientThread extends Thread implements Runnable{
	int playerNum;;
	DatagramSocket socket;
	InetAddress address;
	int port;
	public ClientThread(DatagramPacket packet, int playerNum){
		super("ClientThread");
		
		address = packet.getAddress();
		port = packet.getPort();

		this.playerNum = playerNum;	
	}
	
	public void run(){
		try{
			System.out.println("Thread" + playerNum + ": " + "Accepted. Now creating I/O.\n");
	        
	        while(true){

	        	socket = new DatagramSocket(port);
	        	byte[] buf = new byte[255];
	        	DatagramPacket packet = new DatagramPacket(buf, buf.length);
	            socket.receive(packet);
	        	
	        	ByteBuffer recieveBuf = ByteBuffer.wrap(packet.getData());
				
				recieveBuf.flip();
				System.out.println("Thread" + playerNum + ": " + recieveBuf.toString());
				
				ByteBuffer sendBuf = ByteBuffer.allocate(255);
				sendBuf.asCharBuffer();
				String s = "Thread" + playerNum + ": " + "sent data";
				sendBuf.put(s.getBytes("ASCII"));
				DatagramPacket packet2 = new DatagramPacket(sendBuf.array(), sendBuf.array().length, address, port);
				socket.send(packet2);
	        	socket.close();
		        
		       this.sleep(15);
	        }

		}
		
		catch(Exception e){
			e.printStackTrace();
			System.exit(1);
		}
        
       
	}
	
}

Client


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;


public class TestClient {
	static ClientThread ct;
	static int playerNum = 0;
	
	public static void main(String[] args){
	    	//String ip = JOptionPane.showInputDialog("Input server IP.");
	    	ct = new ClientThread();
		  	ct.start();
		  	ct.setPriority(Thread.MAX_PRIORITY);
		  	
		  	playerNum = ct.playerNum;
	}
}

class ClientThread extends Thread implements Runnable{
	DatagramSocket socket;
	DatagramPacket packet;
	int playerNum;
    boolean loop = true;
    int port;
    byte [] addr;
    InetAddress address;
    
	public ClientThread(){
		super("ClientThread");
		
		try{
			playerNum = 0;
		    System.out.println(playerNum);
		    
		    port = 4445;
		    addr = new byte[] {(byte) 76,(byte) 121,(byte) 76,(byte) 188};
		    address = InetAddress.getByAddress(addr);
		    
		    byte[] buf = new byte[10];
		    socket = new DatagramSocket(4444);
		    DatagramPacket packet = new DatagramPacket(buf, 10, address, 4444);
			System.out.println("send" + address.toString());
			socket.send(packet);
			
		    
		}
		
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void run(){
		try{
			while(loop){
				
				try{
					socket = new DatagramSocket(4444);
					System.out.println("start");
					//byte[] sendBuf = new byte[256];
					ByteBuffer sendBuf = ByteBuffer.allocate(255);
					sendBuf.asCharBuffer();
					String s = "Thread" + playerNum + ": " + "sent data";
					sendBuf.put(s.getBytes("ASCII"));
					
					
					DatagramPacket packet = new DatagramPacket(sendBuf.array(), sendBuf.array().length, address, port);
					System.out.println("send" + address.toString());
					socket.send(packet);
					System.out.println("sent");
					
					byte[] buf = new byte[255];
					packet = new DatagramPacket(buf, buf.length);
					socket.receive(packet);
					ByteBuffer receiveBuf = ByteBuffer.allocate(512);
					receiveBuf.put(packet.getData());

					receiveBuf.flip();
					System.out.println("Thread" + playerNum + ": " + receiveBuf.toString());
					
					
					this.sleep(15);
		        }
				catch(Exception e){
			    		e.printStackTrace();
			    		//socket.close();
			    }  
			}
			
			
			
		}
		
		catch(Exception e){
			e.printStackTrace();
		}
	}
}

Server output:


Waiting for packet from player: 0

Waiting to connect with player: 0

Connected with player: 0 Now incrementing

Incremented to: 1

Waiting for packet from player: 1

Thread0: Accepted. Now creating I/O.

java.net.BindException: Address already in use: Cannot bind
	at java.net.PlainDatagramSocketImpl.bind0(Native Method)
	at java.net.PlainDatagramSocketImpl.bind(Unknown Source)
	at java.net.DatagramSocket.bind(Unknown Source)
	at java.net.DatagramSocket.<init>(Unknown Source)
	at java.net.DatagramSocket.<init>(Unknown Source)
	at java.net.DatagramSocket.<init>(Unknown Source)
	at ClientThread.run(ClientThread.java:24)


Client Exception:


java.net.BindException: Address already in use / at java.net.PlainDatagramSocketImpl.bind0(Native Method) / at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:85) / at java.net.DatagramSocket.bind(DatagramSocket.java:373) / at java.net.DatagramSocket.<init>(DatagramSocket.java:229) / at java.net.DatagramSocket.<init>(DatagramSocket.java:282)
at java.net.DatagramSocket.<init>(DatagramSocket.java:254) / at ClientThread.run(TestClient.java:60)

So can anyone see what I’m doing wrong?

You can’t have 2 sockets open on the same port, as explained by the exception. You are opening a new DatagramSocket on a port that already has another DatagramSocket on it. You have to use the same socket, TestServer.socket, throughout the entire program.

Ah, okay. thank you very much. It works now!

PS: Anyone got any idea how I could test the client/server by myself? asking people to run the client is really slow, and I get port binding issues if I try to run them both myself.

Open a DatagramSocket on the client without a port (if you give a port, it tries to bind it) and just send packets to the server’s port. When you don’t specify a port, the client will pick an open port to use. To send messages back to the client, look at the sender’s port number in the packet received by the server. Use this number to craft a response packet and it will get directed back to the client (which will then listen on its socket).

You can configure your sockets to bind to the “localhost” IP address for testing both sides on your computer.