Reputation: 5316
I'm making a java program & I want this to be both as server and a client (using sockets). How is this best achieved?
Upvotes: 3
Views: 1283
Reputation: 5316
The best way to do this is to run the server on a thread:
You run server.accept()
therefore while your program is listening for a connection on that thread you can do whatever you want on the main thread, even connect to another server therefore making the program both a server & a client.
Upvotes: -2
Reputation: 12770
Have a look at jgroups it's a library that allows the creation of groups of processes whose members can send messages to each other. Another option would be to use hazelcast...
You may also look at this question.
Upvotes: 0
Reputation: 809
If you want each station to function as a server and a client, like a p2p chat,
you should implement a thread with a ServerSocket, listening for incoming connections, and once it got a connection, open a new thread to handle it so the current one will keep on listening for new connections.
For it to be able to connect to others, simple use SocketAddress and Socket, in a different thread to try to connect to a specified server address (e.g. by a list of the user's friends)
you can find plenty of chat examples by googling.
cheers.
Upvotes: 0
Reputation: 421040
If you mean that you want to both send and receive data, a single regular socket (on each computer) will do just fine. See Socket.getInputStream
and Socket.getOutputStream
.
The usual "server" / "client" distinction just boils down which host is listening for incoming connections, and which hosts connect to those hosts. Once the connection is setup, you can both send and receive from both ends.
If you want both hosts to listen for incoming connections, then just set up a ServerSocket
and call accept
on both hosts.
Related links:
Upvotes: 7
Reputation: 18633
If you want the program to perform the same operations regardless of whether it is a server or a client for a certain connection, I could imagine handing off both the client Socket
and the ServerSocket.accept()
-produced socket to the same method for processing.
Upvotes: 0