Client and Server in single file using socket in java - java

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 a class Client extends Thread and class Server extends Thread. Then, from the code initiating the threads (maybe your public static void main() method?) you instantiate both classes, and execute their start() method. Note that start() returns immediately; the code in run() then executes in concurrency. So
a.start();
b.start();
would actually return immediately and then both a and b are running in parallel.

Read this post. This post uses a Java UDP Server and Client code which connects with a Python UDP Client and Server code.
You can make use of Java UDP Server and Client code.

Related

Simulate a couple of clients calling a single Server class in Java

I intend to test a Server class to see how it handles concurrent reads and writes using direct calls to the server class, nothing more fancy. I have a Server API that has two functions.
int fetch(int key);
void push(int key, int value);
How do I create multiple clients making calls to the server? Do I just start multiple threads of a Client class implementing Runnable that call the functions using a static server variable within run()?
Yes, exactly, you should have multiple clients running at the same time on different threads, and they should call the same server object.
Note that with this kind of testing there is no guarantee that you find all the bugs. You should still reason about the thread safety of your code. Possibly you could also use more sophisticated concurrent testing frameworks like multithreadedtc

Java inform a thread from another thread between different classes

Below method runs on main thread in 'Controller' class. It sends request packet to server to get device list.
public List<Device> getDeviceList(){
networkServer.sendMsg(deviceListReqPacket);
//wait till response returns. ???
}
This method runs on another thread in 'Server' class which reads data from server.
private void readDeviceList() {
// read packet from socket
List<nwkDeviceInfo_t> listdevice = networkServerDriver.getDeviceLists(packet);
}
}
What can i do to make getDeviceList() method wait until, readDeviceList() method construct listDevice.And get the listDevice object? Im a little bit confused. Am i trying something not possible or am i doing in a completely wrong way?
If your instances (of the above classes) run on the same JVM but in different threads, use one of the blocking queues that come with Java.
If they communicate over a network (e.g. HTTP and such) seems like the read would block until the write is done (and indeed received on the other side). So in that case, you already have the behaviour you want.

Thread or class for doing nothing until a method is called

I want to open a tcp socket in java and from time to time call a send-method from other applications.
All that has to be done is waiting until the send method is called and returning the answer to the request. I was wondering if I should use a thread holding the tcp connection and the send/receive method or just a class where I can avoid the "do-nothing-part-until-send-is-called".
In either case I would create a separate class, perhaps a Singleton or a static class. Then I would call it when I need it.
Now if I wanted to make it a thread then it would need to meet some criteria. Should it run parallel to anything else? Will it hold back any other code trying to execute?
Since you are using a TCP socket then there might be a good chance that it could hold back execution of other code in perhaps a server you plan to run.

How to get control over multiple client threads connecting to a RMI Server

Stolen from:
http://publib.boulder.ibm.com/infocenter/javasdk/v1r4m2/index.jsp?topic=%2Fcom.ibm.java.doc.diagnostics.142%2Fhtml%2Fid1418.html
"on the server side, when a client connects to the server socket, a new thread is forked to deal with the incoming call. "
so how can i get a control over these client threads so that i can make my client 1 wait till client 2 shows up and then perform whatever they need to perform?
Thank you.
I agree with #EJP that this is a very strange requirement. The solution I will offer should work but is normally something you absolutely don't want to do, because it blocks a thread causing bad usability and scalability.
You can achieve this using a CountDownLatch
Have a static CountDownLatch set to 1
public class RmiEndPoint{
static CountDownLatch startSignal = new CountDownLatch(1);
Client 2 counts it down
public void executedByClient2(){
SharedLock.countDown();
}
Client 1 waits on it
public void executedByClient1(){
SharedLock.await();
// do whatever you want to do
}
}
In real code you definetly want to have some timeouts so your app doesn't hang for ever if client2 doesn't show up
You can't get control of the threads, but you don't need it. You have do control over the remote methods. Just put whatever synchronization, acting, semaphores etc. that you need inside your remote method implementations.
Having said that, it's a very strange requirement. Normally clients are independent of each other.

How to have a run in an Service?

I have implemented an service that runs in a seperate process.
This service contains a separate thread where i have a socket connection.
This thread has a run() where it is continuously sending data to the port.
My problem is after triggering the run() in the thread i don't get any contact with it anymore, i can see in the program that have open the socket that it consciously sends the data but the idea was that i while it is running i could change data that it sends for an example time.
here is my run in the external thread:
public void run()
{
if(run)
{
// Team and player names message is sent when entering in a game
setBaseMessage();
SendMessageToCOMPort(base_message + CalculateCRC(base_message));
sleep(); // waits for 100 ms
}
}
Anyone have any idea what might be wrong ?
I did not quite get your problem. It seems that you want to run a separate thread in your service which does some socket communication. Furthermore you want to be able to influence the data the thread is sending using the socket.
I have implemented an service that runs in a seperate process.
First of all, android services aren't running in a separate process or thread by default. Therefore, to run long running operations you have to develop multithreading by your self using Java threading and implementing the run method as you have done it.
Threads of a single process share the same memory. Therefore, to influence what the socket thread is doing, you can use data structures like a queue or a list which are shared among the threads. For example, you could apply the producer-consumer pattern. The producer passes data to a shared queue. The consumer consumes the data from the queue and processes it. However, be aware that you have to synchronize the access to the shared queue.
I hope I was able to clarify the issue and give you some advice to solve the issue.

Categories

Resources