I have an Erlang server which is spawning a new process for each client that connects. Then the Pid of this new process is passed to the client (to make a connection to the new process.) Is that enough to make a connection from a jinterface client?
I am using this to connect from the client first:
final String SERVERNAME = "server";
final String SERVERNODE = "bertil#computer";
mbox.send(SERVERNAME, SERVERNODE, connectClient);
And those names is set in the server when it starts:
start() ->
net_kernel:start([bertil, shortnames]),
register(server, self()).
Do I have to register a new name for each spawned process? That would not be so dynamic... How do I solve this? Should I use the main process at the server as a router to send all traffic through?
Once you have a pid, you should be able to send a message directly to it. In Erlang you don't have to specify a node if you got a pid. You only need a node if you are sending to a registered name since names are only unique per nod. Pids are unique in the whole cluster.
If you have a varable my_pid as an OtpErlangPid object you can send like so:
mbox.send(my_pid, message);
See the documentation for the send function and chapter 1.6 Sending and Receiving Messages in the Jinterface User's Guide.
Related
I did a simple chatserver in the java ... I'm wondering about adding a username to a chat that you need to enter when you enter chat. Also, I do not understand how private messages are sent only to the addressee
If the destination is not logged in to the chat server, the error message should be sent to the sender
Each message sent by the server to the client must be accompanied by the name of the original sender and the time when the message was sent.
Java Code ---> https://dijaspora24.info/?page_id=4123
I am not going to show the implementation, since it's a big problem to solve here. However, I will give an idea of how to implement this.
I assume you know how to connect a client to a server (for example by using ServerSocket and Socket).
First, to add the username of a connected client, the server simply has to force the client enter a string to the server as the first thing when it connects to the server.
Second, create a Map to store all clients, where key is the username entered and value is the socket.
Third, when a client want to send a message to another client, some format must be used to send a string that is understandable by the server. When sending a string to another client, the username of the receiving client must be within the string. When the server receives the string, it extracts the username of the receiving client's username and locates the client in the Map by its key. As mentioned, the value of the Map element is the socket instance of the client you want to send to.
To make all of this possible, a thread must be used for each client that listens for input from each client.
I'm creating a Java program, based on the client-server model in which I need the server and the client(s) to communicate.
More specifically I need them to "give orders" to each other or request things, and transfer data inside those orders/requests, you can see what I'm trying to achieve looks something like a method, but instead of happening locally, those "methods" are called by one side and executed by the other.
For instance a possible scenario is:
The server is listening for orders
The client tries to authenticate
and sends username and password to the server
The server receives
the authentication request, controls whether the username and
password are correct and reports back to the client
The client is
now authenticated
The server is once again listening for orders
Now, my first idea was to use DataInputStream and DataOutputStream, sending requests under the form of strings, for instance, if I wanted the client to request authentication I would do something like this:
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("requestAuth");
dos.writeUTF(username);
dos.writeUTF(password);
and the server:
DataInputStream dis = new DataInputStream(socket.getInputStream());
if(dis.readUTF().equals("requestAuth")){
String username = dis.readUTF();
String password = dis.readUTF();
//Check whether they're correct or not bla bla bla
}
This doesn't seem like the best option to me, I think there's better ways to do this but I just don't know how, I already searched for a better solution but found nothing.
Another problem that arised is that I need both the server and the client to be able to send those requests simultaneously and these requests can be sent anytime, asynchronously.
For instance: let's say the client is authenticating, it's sending the username, password, etc... but meanwhile the server wants to check if the client is still connected because a Thread is doing it every second, how can I make sure each information is delivered in the right place without the stream clogging up or threads receiving unwanted data? If the client is waiting to know whether the username and password are correct, I don't want to clog it up with the request of the other thread that's doing something completely different.
Basically: my client/server program can be multithreaded, can sockets too without things getting messy? Can I have thread ServerA communicating with thread ClientA, and thread ServerB communicating with thread ClientB without interferring with each other? Can I have multiple streams from the same socket and work on them separately?
I want to send data to my connected clients, but I want to send the message only to one specific user. I don't know how to accomplish this. Do I have to use the client's IP address or what? I'm programming in Java with sockets.
you need to add connected connection in some collection.
Socket client = serverSocket.accept();
map.put("someKey", client);
when you have to send message to any specific client. just get his connection from map by giving its key.
Socket clnt = map.get("someKey");
// further processing.
in c# you can use dictionary in place of maps.
You have to keep track of the clients that connect to your server. Most likely using a client ID with a Key/Value collection (try looking up Map).
I would like to have this setup:
Server hosting TCP socket server
Multiple clients connected over TCP (keeping connection open)
Then I would like to initiate a message from the Server to the client. I can't figure out how to do this, and have multiple client sessions at the same time. Techniques I've read involve the Server listening on a port, and when it receives communicate from a client, it launches a new thread to handle and process that, and then it goes back to listening on the port for the next request of another client.
So, then how would I tap into that and send a message to a client running on one of those threads?
My actual usage scenario if you are interested is below. Final goal is like a remote control for your file system to upload files to the server.
- Each client has a java background application running in the system tray that connects to the server
- Server hosts connections, and also hosts a RESTFul webservice to initiate communication
- Mobile device connects to Server over RESTFul webservices to request informatino about the client's filesystem. So it can drill down and find a file, then click and have the file uploaded to the server.
The idea here is mobile users needing to upload files from their desktop to the server while away from their office on a mobile device. (and this is for custom product, so can't use a third-party app_
PS: I've been looking at the simple Client-Server chat program here: http://way2java.com/networking/chat-program-two-way-communication/
You want to have a server listening at all times on a specified port. Once the server notices an incoming connection on that port you should create a new Thread to handle the communication between that client and the server, while the main thread keeps on listening for other incoming connections. This way you can have multiple clients connected to one server. Like so:
private void listen() throws IOException {
serverSocket = new ServerSocket(port)
while (GlobalFlags.listening) {
new ServerThread(serverSocket.accept();
if (GlobalFlags.exit) {
serverSocket.close();
break;
}
}
}
Where the GlobalFlags are variables to control the listening process and are not really necessary. You could do a while True and just keep listening for ever and ever.
In my project I have a main server controller which had listeners running in Threads. The controller controlled the GlobalFlags. I'm sure instead of using global flags there is a better way to do inter thread communication but for me this was the simplest at the time.
The ServerThread should be looping all the time switching between sending output to the client and receiving input from the client. Like so:
ServerThread(Socket socket) {
super("GameServerThread");
this.socket = socket;
try {
this.socket.setTcpNoDelay(true);
} catch (SocketException e) {
// Error handling
}
this.terminate = false;
}
#Override
public void run() {
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
outputLine = processInput(inputLine);
out.println(outputLine);
if (terminate) {
break;
}
}
}
out.close();
in.close();
socket.close();
} catch (Exception e) {
// Error handling, should not use Exception but handle all exceptions by themselves.
}
On the client side you have a thread running through a similar loop, receiving input from the server and then sending output to the server.
In this example processInput is the function used to process the client's input. If you want the server to initiate contact you can make the server send something to the outputstream before listening for input and make the client listen first.
I have extracted this example from one of my own projects and the this.socket.setTcpNoDelay(true) is supposed to make the process faster. Reference here: http://www.rgagnon.com/javadetails/java-0294.html
"java.net.Socket.setTcpNoDelay() is used to enable/disable TCP_NODELAY which disable/enable Nagle's algorithm.
Nagle's algorithm try to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. The Nagle's algorithm is described in RFC 896.
You get the current "TCP_NODELAY" setting with java.net.Socket.getTcpNoDelay()"
So to send a message to a specific client you could put all the threads upon creation in an ArrayList so you can keep track of all the currently connected clients. You can have the processInput method halt and polling a queue/variable until another class puts the message to be send in the queue/variable. So how to gain a handle on the class depends on your implementation of processInput. You could give every thread an ID (which is what I did in my project) and maybe have the processInput method poll an ArrayList at index=ID. Then to send output to the client you would have to set the variable at index=ID.
This method seems kind of clunky to me personally but I'm not really sure how else I would do it. You would probably use Queues and have processInput write the input to its Queue and then wait for another class to read it and put its response in the Queue. But I have personally never worked with Queues in java so you should read up on that yourself.
In my knowledge
1) Server hosting TCP socket server -- Possible
2) Multiple clients connected over TCP -- Possible
3) Then I would like to initiate a message from the Server to the client -- Not Possible. The Client has to initiate a connection creation, then the server might be able to send data packets to You. Example: You need to open Facebook website on your browser, Facebook server cannot decide to send its page to your PC on its own because your PC will not have a static IP address, and also if Facebook hypothetically writes code to initiate connection to Your PC, then it is as good as Your PC is the server and Facebook website/server acts as client.
I have 3 .jsp's. The first one asks the user for their username. Once the form is submitted it is taken to a 2nd jsp where a unique passcode is created for the user. How would I go about taking this passcode and passing it to a 3rd jsp using a socket?
You can use java.net.URL and java.net.URLConnection to fire and handle HTTP requests programmatically. They make use of sockets under the covers and this way you don't need to fiddle with low level details about the HTTP protocol. You can pass parameters as query string in the URL.
String url = "http://localhost:8080/context/3rd.jsp?passcode=" + URLEncoder.encode(passcode, "UTF-8");
InputStream input = new URL(url).openStream();
// ... (read it, it contains the response)
This way the passcode request parameter is available in the 3rd JSP by ${param.passcode} or request.getParameter("passcode") the usual way.
Better is however to just include that 3rd JSP in your 2nd JSP.
request.setAttribute("passcode", passcode);
request.getRequestDispatcher("3rd.jsp").include(request, response);
This way the passcode is available as request attribute in the 3rd JSP by ${passcode} or request.getAttribute("passcode") the usual way.
See also:
Using java.net.URLConnection to fire and handle HTTP requests
Unrelated to the concrete question, this is however a terribly nasty hack and the purpose of this is beyond me. There's somewhere a serious design flaw in your application. Most likely those JSPs are tight coupled with business logic which actually belongs in normal and reuseable Java classes like servlets and/or EJBs and/or JAX-WS/RS which you just import and call in your Java class the usual Java way. JSPs are meant to generate and send HTML, not to act as business services, let alone web services. See also How to avoid Java code in JSP files?
So, you want the username to be submitted from the first JSP to the second, by submitting a form to the second, right?
But, for interaction between the second and third, you want to avoid using the communication mechanisms behind the the JSP files and use your own, right?
Well, how you might implement doing this depends on where you're sending your communication from and to. For instance, are they on the same machine, or on different machines?
Generally speaking, you'll need a client-server type of relationship to be set up here. I imagine that you would want your third JSP to act as the server.
What the third JSP will do is will sit and wait for a client to try to communicate with it. But, before you can do that, you'll first need to bind a port to your application. Ports are allocated by the Operating System and are given to requesting processes.
When trying to implement this in Java, you might want to try something like the following:
int port_number = 1080;
ServerSocket server = new ServerSocket(port_number);
In the above example, the ServerSocket is already bound to the specified port 1080. It doesn't have to be 1080 - 1080 is just an example.
Next, you will want to listen and wait for a request to come in. You can implement this step in the following:
Socket request = null;
while((request = server.accept()) == null)
{}
This will cause the server socket to keep looping until it finally receives a request. When the request comes in, it will create a new Socket object to handle that request. So, you could come back to your loop later on and continue to wait and accept requests, while a child thread handles communication using your newly created request Socket.
But, for your project, I would guess that you don't need to communicate with more than one client at a time, so it's okay if we just simply stop listening once we receive a request, I suppose.
So, now onto the client application. Here, it's a little bit different from what we had with the server. First off, instead of listening in on the port and waiting for are request, the client's socket will actively try to connect to a remote host on their port. So, if there is no server listening in on that port, then the connection will fail.
So, two things will need to be know, those are:
What's the IP Address of the server?
What port is the server listening in on?
There are short-cuts to getting the connection using the Java Socket class, but I assume that you're going to test this out on the same machine, right? If so, then you will need two separate ports for both your client and server. That's because the OS won't allow two separate processes to share the same port. Once a process binds to the port, no other process is allowed to access it until that port releases it back to the OS.
So, to make the two separate JSP's communicate on the same physical machine, you'll need both a local port for your client, and you'll need the server's port number that it's listening in on.
So, let's try the following for the client application:
int local_port = 1079;
int remote_port = 1080;
InetSocketAddress localhost = new InetSocketAddress(local_port);
Socket client = new Socket(); //The client socket is not yet bound to any ports.
client.bind(localhost); //The client socket has just requested the specified port number from the OS and should be bound to it.
String remoteHostsName = "[put something here]";
InetSocketAddress remotehost = new InetSocketAddress(InetAddress.getByName(remoteHostsName), remote_port); //Performs a DSN lookup of the specified remote host and returns an IP address with the allocated port number
client.connect(remotehost); //Connection to the remote server is being made.
That should help you along your way.
A final note should be made here. You can't actually run these two applications using the same JVM. You'll need two separate processes for client and server applications to run.