I read through the method to connect to a socket server : http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_5.html
I wrote an AIR application to connect to the java server code, but the client cannot connect. What is missing in the code?
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" backgroundColor="#D5F8C3">
<fx:Script>
<![CDATA[
import flash.net.XMLSocket;
var socket:XMLSocket;
public function b1_clickHandler(event:MouseEvent):void
{
var socket:XMLSocket;
socket.connect("127.0.0.1",8080);
socket.send("Hello");
//socket.addEventListener(DataEvent.DATA, onData);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button id="b1" x="285" y="162" label="Send Text" width="201" height="105" click="b1_clickHandler(event)"/>
</s:WindowedApplication>
You have to wait for CONNECTED event before sending data. Also, be sure you've managed crossdomain security (look at : http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7c60.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7c63)
Server/client code exemple : Air 2 ServerSocket Crossdomain problem
Related
I have server actor running in the background. The basic operation of the server actor is to get a key and a value pair. Once it receives the pair, it stores it in a map and returns it when asked.
Now, I have a client actor. I want to the connect to the server actor using actorSelection() method. But I am confused with the parameters it takes. Can anyone help me understand what parameters it takes ?
Server side:-
Actor System: actorSystem
Server Actor: akkademy-db
Client side:-
Actor System: LocalSystem
You didn't mention that your scenario is from the book Learning Akka. As stated in the book, the client can obtain an ActorSelection of the server with the following:
ActorSelection remoteDb = system.actorSelection("akka.tcp://akkademy#" + remoteAddress + "/user/akkademy-db")
The template for the path, as the documentation describes, is the following:
akka.<protocol>://<actor system name>#<hostname>:<port>/<actor path>
Using the template, here's a breakdown of the ActorSelection path to the server:
"akka.tcp://akkademy#" + remoteAddress + "/user/akkademy-db"
// tcp --> protocol
// akkademy --> actor system name
// remoteAddress --> hostname:port
// /user/akkademy-db --> actor path
Read the documentation for more information.
Okay, so I have an apache server that has text/data that I want to sendoff to a Java client. The issue is that the data will change often, and I don't want the client to constantly do a read on the server, because obviously I don't want a constant ping. I know that I can make a client socket but that requires my users to port forward to access the server, which isn't going to work for my users.
What I've found online is UDP punching may work or NAT Transfer, but I cant find any examples for how to do it in Java.
If you have any questions please feel free to comment :)
You could Recieve Server-Sent Event notifications, in which the server send the data, using PHP and JS as an example:
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
PHP:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
I have one index.jsp file, one connect.java servlet and one Server.java file which creates a chat server.
index.jsp
<form action="connect">
<textarea name="chat-window" ></textarea>
<input name="port-number" placeholder="enter-port"/>
<select name="action-type">
<option> start </option>
<option> stop </option>
<option> refresh </option>
</select>
<button name="apply-btn" type="submit"> apply </button>
</form>
connect servlet
// creates new thread(runnable) to run Server.java and
// passes portNumber, printWriter object generated by response.getWriter() to Server.java
Server.java
// creates serverSocket on portNumber
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
showException("Server.startRunning(): new ServerSocket() ", e);
}
printWriter.println("Server is online at " + portNumber + " \n");
It prints Server is online at XXXX
But, after this, i think printWriter becomes unusable, maybe entire link of index.jsp page to threaded Server.java object gets broken. Because, form action="connect" is completely performed and server is started and it doesn't wait for clients to get connected.
now, if i add following to Server.java
while(true) {
try {
clientSocket = serverSocket.accept();
printWriter.println("Client Connected.");
// JOptionPane.showMessageDialog("Client Connected.", null);
} catch() {
// Exception handling mechanism
}
}
and if, now, client connects to Server, printWriter statement doesn't print anything (maybe because the actual web-page needs to be refreshed, but why? how can i make it dynamic if this is the problem? ).
I can verify that client gets connected successfully because if i uncomment the JOptionPane statement, it shows when a client gets connected. So, no issues on client-side.
How can i make the printWriter statement work? Somehow, keep the connection between JSP and Server.java alive. Make the Servlet/JSP continuously listen to Server.java
index.jsp view
connect.java servlet view
I didn't have a perfect title for this question.
If this is impossible, kindly write an alternative.
Don't do that. Passing around HTTP request/response related state to a different thread outside the HTTP thread is recipe for disaster. Once the servlet doXxx() method returns, then the request/response objects and all of its related state are garbaged (simply because they're finished doing their HTTP based job) and become unusable (so any attempt to use them anyway would only result in unexpected behavior or exceptions like IllegalStateException). Never do that.
As to your concrete functional requirement of opening a persistent two-way client-server socket connection, you seem to be confusing desktop applications with web applications while searching for solutions. The code which you've there would only work for desktop applications.
For web applications, you need web sockets instead. Use JavaScript's window.WebSocket API in client side (tutorial here) and Java EE's javax.websocket API (JSR356) in server side (tutorial here).
Do note that this API is very low level, it's nearly as low level as HTTP. For instance, in the Servlet API you have "session" scope ready for direct use and you can easily identify users and all, but in WebSocket API not. You have to (re)invent and code all the scopes/layers yourself. If you can, rather go for an existing library/framework. For example, Java EE's own MVC framework JSF has several libraries (plugins) available for the job, such as OmniFaces <o:socket> tag which is demonstrated here (and developed by yours truly).
See also:
Real time updates from database using JSF/Java EE
How to propagate CDI session beans from HTTP session to WebSocket session?
I'm trying to configure Spring on the server side to open a socket, listen for connections and take the incoming stream (converting to String).
But I cannot find any working examples on how to just create such an incoming tcp connection. This is what I have (taken from an incomplete example):
<int-ip:tcp-connection-factory id="cfServer"
type="server"
port="8080"
using-nio="true"
single-use="true" />
<int-ip:tcp-inbound-channel-adapter id="inboundServer"
channel="loop"
connection-factory="server"/>
<int:channel id="loop"/>
Well, but how do I continue? How can I acutally bind these adapters to a backing class? And what do these classes have to look like?
Subscribe something to the loop channel, e.g. a <service-activator/>.
See the tcp-client-server sample
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
A PHP Socket Server with Flash Clients
I am building an app in my server with the help of a flash developer, and he asked me to build a socket server to communicate with the database. He recommended me JAVA but I am not very good at JAVA and I was wondering if it was possible to build a Socket Server in PHP.
I should allow connections to multiple TCP client connections. I know in JAVA this is done thought threading, but I am not sure if this can also be achieved with PHP.
Could someone please show me the basic skeleton of a PHP Socket Server with these characteristics?
The connection has to be TCp (persistent) from the beginning of the connection to the app, until the end.
You have to run your socket server as a service from the command line.
This is a part of what I have used before. It closes the socket after a read but can easy be modified to keep a array of connections.
You would have to build some kind of watchdog to see if a connection is still alive.
You need a identifying mechanism to identify different connections.
The code:
set_time_limit( 0 );
// Set the ip and port we will listen on
$address = '127.0.0.1';
$port = 6789;
// Create a TCP Stream socket
$sock = socket_create( AF_INET, SOCK_STREAM, 0 ); // 0 for SQL_TCP
// Bind the socket to an address/port
socket_bind( $sock, 0, $port ) or die( 'Could not bind to address' ); //0 for localhost
// Start listening for connections
socket_listen( $sock );
//loop and listen
while (true) {
/* Accept incoming requests and handle them as child processes */
$client = socket_accept( $sock );
// Read the input from the client – 1024000 bytes
$input = socket_read( $client, 1024000 );
// from here you need to do your database stuff
// and handle the response
// Display output back to client
socket_write( $client, $response );
socket_close( $client );
}
// Close the master sockets
socket_close( $sock );
There is a WebSocket Server and Client library for PHP At Google code . It supports flash clients . Not sure whether it solves your problem .
If you want a basic tutorial here is the link to learn
How to create a socket server in php
EDIT :- after looking at your comment ( running a socket server continuously as a service )
Here is the link which describes the way of creating a socket server and running as a process
Create a socket server in php and run as a service
Rather than building a "socket server", you should really build a set of web APIs (SOAP, REST/JSON, whatever) that provides limited and well-defined access to the DB. Then have the Flash app use that.
Your flash app sends JSON over a RESTful interface, or SOAP/XML requests. The server receives them, interacts appropriately with the database, and returns any required results again as XML or JSON.