Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

A java program to act as both TCP client and server

843790Oct 6 2007 — edited Oct 7 2007
How do i make a single program act as both client and server (TCP). In the sense i should be able to run instances of the same program as a server in one place accepting connection and the client requesting connection to this server (running the same code) running somewhere else.


Thanks

Comments

843790
Server code and client code are (at least in my view) not the same. Unless you are talking about some peer-2-peer architecture. Take a look at java.io.ServerSocket and java.io.Socket.
843790
Ya in the context of a peer to peer architecture, i would want a single program capable of acting as a server and a client, with multiple instances of this program executing at the same time.
843790
Then you need both a ServerSocket instance and corresponding thread that accepts incoming connections. And Socket instances for outgoing connections. Or their equivalents in the NIO case.

Maybe you would also require something like a peer table mechanism. For organizing the incoming and outgoing connections.

Could you give some more context? Might make it easier to give pointers...
843790
the architecture goes something like this.

i have a peer to peer system wherein every node (single java program) acts as a client and server. So tht program should hav conditions tht make it behave like a client or a server when needed.
843790
Well as I said: take a look at java.io.ServerSocket and java.io.Socket. I don't think the point of forums like these are here to give you a compile ready solution (not even a long shot) for problems like this.

So my suggestion is take a look at the aforementioned classes. But first take good look at the real architecture. And at your problem area. Maybe there is something already out there that does the trick. Or in case of a mental/personal/educational exercise think about tools/platforms you can use. You could go for the Socket programming solution (java.io.*), even for a non-blocking TCP level solution (java.nio.*). But there are also lots of other things to look at, SOAP might be a solution. Or RMI or Jini with JERI. Maybe even a messaging platform such as JMS...

Final hint: Nodes in a p2p environment are (as far as I know) always equal in their relationship. So they both listen for incoming connections, and can create outgoing ones. But it doesn't matter for the communication who initiated it.
1 - 5
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Nov 4 2007
Added on Oct 6 2007
5 comments
451 views