user1679463
user1679463

Reputation: 23

java p2p without any framework

I need to develop a p2p application that DOES NOT use any framework like JXTA. I searched through various topics in StackOverflow but I am not getting what I want. I have a server that maintains the list of clients and its resources. The clients will contact the server to find out which client has what. After the client gets this info from the server, it will establish a p2p connection with the other client - the server is not involved in this.

I need to know as to how to create a client socket and a server socket in the same program i.e the program should like a server and client. Please help me out.

for ex:
 client code 
 Socket clientSocket = new Socket("localhost", 10000);

 server code
 ServerSocket welcomeSocket = new ServerSocket(10000);

     while(true)
     {
        //client socket
        Socket connectionSocket = welcomeSocket.accept();
        .......
        .......
     }

How will I add a serversocket to my client and make it work like a server? I know I have to use threads, but can anyone explain this in detail? or please post a RELEVANT thread.. I am tired of looking through various forums and websites..

Upvotes: 0

Views: 1385

Answers (1)

Eero Aaltonen
Eero Aaltonen

Reputation: 4425

There are actually many ways to write networking code with respect to threads and IO (see http://www.kegel.com/c10k.html). I guess the traditional way is to create a thread to handle each connection, explained in the bottom of the Java tutorial. This is perfectly fine, if the connection is established, does something, and is then closed.

However, if you keep connections open all the time you may end up creating too many threads and overhead. Hence, the other approaches.

Also, you should consider using some general java networking library. You can implement your own protocol and communication model, but still save some effort and probably end up with better code.

Upvotes: 1

Related Questions