Can anyone please tell me how to create a server and client (both) in a single file?
I searched the net and came to know that it is possible using the threads. I am not familiar with threads. I am trying to implement a peer to peer application. At some point, the peer has to behave as server and client. Can anyone please give a sample code or direct me to a good source?
Put simply, threads are parallel workflows that execute your code. So if you have two instances of threads, you can have one of them execute method A, and one of them execute method B, and both will occur concurrently. The art and science of writing concurrent code is very advanced and takes a long while to master.
However it’s very easy to begin. For each piece of code you want to run separately, you create a class extending Thread, and put the code to be run in the overridden
run()method. In your case, that could be aclass Client extends Threadandclass Server extends Thread. Then, from the code initiating the threads (maybe yourpublic static void main()method?) you instantiate both classes, and execute theirstart()method. Note that start() returns immediately; the code inrun()then executes in concurrency. Sowould actually return immediately and then both a and b are running in parallel.