Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (487)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (553)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  java.net.BindException: Address already in use: Cannot bind  (Read 7054 times)
0 Members and 1 Guest are viewing this topic.
Offline CyanPrime
« Posted 2011-05-11 18:09:41 »

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:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
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)
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
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
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
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:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
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:
1  
2  
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?
Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2011-05-11 18:41:22 »

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.

Offline CyanPrime
« Reply #2 - Posted 2011-05-11 19:05:17 »

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.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline lhkbob

JGO Knight


Medals: 32



« Reply #3 - Posted 2011-05-11 19:14:04 »

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.

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

TehJavaDev (16 views)
2014-08-28 18:26:30

CopyableCougar4 (25 views)
2014-08-22 19:31:30

atombrot (38 views)
2014-08-19 09:29:53

Tekkerue (35 views)
2014-08-16 06:45:27

Tekkerue (32 views)
2014-08-16 06:22:17

Tekkerue (20 views)
2014-08-16 06:20:21

Tekkerue (32 views)
2014-08-16 06:12:11

Rayexar (66 views)
2014-08-11 02:49:23

BurntPizza (44 views)
2014-08-09 21:09:32

BurntPizza (35 views)
2014-08-08 02:01:56
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!