Java server PHP Client - java

I want to implement a java server and a php client. Every time a click is done on the website (php client) a action should be executed on the server.
Actually my server looks like:
public static void main(String args[]) {
System.out.println("Signal Server is running.");
try {
socket = new ServerSocket(port);
while (true) {
connection = socket.accept();
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
DataOutputStream response = new DataOutputStream(connection.getOutputStream());
BufferedReader input = new BufferedReader(inputStream);
command = input.readLine();
response.writeBytes(responseStr);
response.flush();
System.out.println("Running");
}
} catch (IOException e) {
System.out.println("Fail!: " + e.toString());
}
System.out.println("Closing...");
}
My HTML site looks like:
<?php
if (isset($_POST["Btn1"])){
$address = "localhost";
$port = 4343;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$message = 'blablabla';
socket_connect($socket, $address, $port);
socket_sendto($socket, $message, strlen($message), 0, $address, $port);
};
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<form id="form1" method="POST">
<button type="submit" form="form1" id="Btn1" name="Btn1" value="Btn1" title="Btn1">
Btn1</button>
</form>
</body>
</html>
My problem is, whats the best way to delegate the actions to the server. A little example, I have a method on my java server which posts "Hello" to the console. Now I click on a button on my website and this method should be executed. What is the best way to do?
Can I use my approach or is there a better one?

PHP runs server-side, so you cannot execute PHP code on the client's web page...

Related

Java Sockets + socket.io-client (Angular 13) = Failed connections and scrambled messages

I am trying to use a Java Socket Server with socket.io-client, but it has an erratic behavior from the moment of the connection. It manages to stablish connection, but then this exception is thrown in Angular:
GET https://127.0.0.1:1532/socket.io/?EIO=4&transport=polling&t=N__rEfS net::ERR_SSL_PROTOCOL_ERROR
And the Server in Java only receives scrambled text repatedly
and the Client starts connecting and disconnecting over and over again. Why is this happening? Is there any way to get a cleaner Socket connection from Angular 13 to Java?
I use this Java Socket Server for many other applications and it works perfectly for everything else but this.
This is the routine that reads the Java Server:
void handleClientRequest() {
try{
mBufferIn = new BufferedReader(new InputStreamReader( socket.getInputStream()));
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//in this while the client listens for the messages sent by the server
while (clientRun) {
String clientMessage = mBufferIn.readLine();
if (clientMessage != null && mMessageListener != null) {
mMessageListener.messageReceived(clientMessage);
}
}
} catch(Exception e){
System.out.printf("%s: Unexpected client disconnection. Reason:%n", accountId);
e.printStackTrace();
}
}
And this is the Angular code:
this.socket = io('https://127.0.0.1:1532');
this.socket.on('connect', () => {
const engine = this.socket.io.engine;
console.log(engine.transport.name); // in most cases, prints "polling"
engine.once('upgrade', () => {
// called when the transport is upgraded (i.e. from HTTP long-polling to WebSocket)
console.log(engine.transport.name); // in most cases, prints "websocket"
});
engine.on('packet', ({ }) => {
// called for each packet received
});
engine.on('packetCreate', ({ }) => {
// called for each packet sent
});
engine.on('drain', () => {
// called when the write buffer is drained
});
engine.on('close', (reason: any) => {
// called when the underlying connection is closed
});
});
Code taken from https://socket.io/docs/v4/client-socket-instance/
Socket IO is a communication protocol implemented on the top of websocket
from my understanding (correct me if im wrong) you are using raw socket in java.
So very likely that "scrambled" text that you are receiving, is part of https handshake.
My suggestion as way forward, will be to use library that handles websocket connections.

I need to connect a client TCP created in java with a HTTP servant created with node.js

I need to connect a client TCP created in java with a HTTP server created with node.js
I want that on having done click on a button of my HTML an operation executes in the client java via sockets using the module net.
My code HTML:
<body>
<button id="bt1">Button 1</button>
<button id="bt2">Button 2</button>
<button id="bt3">Button 3</button>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
socket.emit('tcp', "For TCP");
});
</script>
</body>
My code java client:
class ClientSocket{
public static void main(String[] args){
String address = "127.0.0.1";
int port = 5555;
try {
Socket socket = new Socket(address, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ope = in.readLine();
if(ope.equals("1")){
System.out.println("You pulsated on the button 1");
}else if(ope.equals("2")){
System.out.println("You pulsated on the button 2");
}else if(ope.equals("3")){
System.out.println("You pulsated on the button 3");
}
// ........
in.close();
socket.close();
}catch( IOException e){
System.out.println(e);
}
}
}
My code node serverTCP.js:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 5555;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1"); // No send
console.log('Server listening on ' + server.address().address +':'+ server.address().port);
}).listen(PORT, HOST);
My code node serverHTTP.js:
var http = require('http').createServer(httpHandler), fs = require("fs"), wsock = require('socket.io').listen(http), tcpsock = require('net');
var http_port = 8080;
var tcp_HOST = '127.0.0.1';
var tcp_PORT = 5555;
/**
* http server
*/
function httpHandler (req, res){
fs.readFile(__dirname + '/index.html',
function(err, data) {
if(err){
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function(socket){
var tcpClient = new tcpsock.Socket({allowHalfOpen: false, readable: true, writable: true});
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function(){
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data){
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data){
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message){
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
Better use a http server for that. Use Tomcat and create a simple Servlet will fix your problem.
Otherwise you need to listen on the port and accept incoming requests using separate tasks. Thats more complex then your sample code. See http://www.oracle.com/technetwork/java/socket-140484.html

Server Sent Events Android

I want to use Server Sent Events in my WebView on Android (4.4). The EventSource should connect to a local Port (5003) where I have a ServerSocket listening for incoming requests:
Socket _socket;
//Creating Server Socket listening on Port 5003
try {
InetAddress adress = InetAddress.getByName("localhost");
ServerSocket serversocket = new ServerSocket(5003, 50, adress);
while(true){
_socket = serversocket.accept(); //Accept incoming request
Logger.Log.d("SSE","Received Server Sent Event Request);
}
} catch (IOException e) {
e.printStackTrace();
}
The JavaScript from my HTML Page:
var source = new EventSource('http://localhost:5003/');
source.addEventListener('message', function(e) {
console.log(e.data);
}, false);
source.addEventListener('open', function(e) {
// Connection was opened.
console.log('open');
}, false);
source.addEventListener('error', function(e) {
var txt;
switch( event.target.readyState ){
// if reconnecting
case EventSource.CONNECTING:
txt = 'Reconnecting...' + event.target.url;
break;
// if error was fatal
case EventSource.CLOSED:
txt = 'Connection failed. Will not retry.';
break;
}
console.log(txt);
}, false);
The EventSource doesn't connect to my local socket.
Every 3 seconds the onError is called and the EventSource tries to reconnect.
I/chromium(15898): [INFO:CONSOLE(24)] "Reconnecting...http://localhost:5003/"
Can anybody please help me?
I solved the problem myself.
The code is working. I only had to reset my Android device to factory defaults.
Now everything works perfectly.

Unable to connect via websocket connection

I'm trying to create a simple Websocket connection in my project.
Java code:
#ServerEndpoint("/echo")
public class EchoEndpoint {
#OnMessage
public void onMessage(Session session,String message){
try{
System.out.println(message);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
html and javascript code:
<button type="button" onclick="WebSocketTest()">Send</button>
<script type="text/javascript">
function WebSocketTest()
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
</script>
after pressing the button I got the errorWebSocket connection to 'ws://localhost:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 404
Jboss Wildfly8 is used as Application Server.
Any Idea? or any working example?
This is because you put wrong path here:
var ws = new WebSocket("ws://localhost:8080/echo");
if your application is packed to eg: websocketapp.war (or if you set context-path on websocketapp)
then you should use:
var ws = new WebSocket("ws://localhost:8080/websocketapp/echo");
Connecting to web-socket For example
var webSocket= new WebSocket("ws://l92.168.1.27:50333/project name//serverendpointdemo");
var messagesTextArea=document.getElementsByClassId("messagesTextArea");
webSocket.onopen=function(message){processOpen(message);};
webSocket.onclose=function(message){processClose(message);};
webSocket.onmessage=function(message){processMessage(message);};
webSocket.onerror=function(message){processError(message);};
function processOpen(message){
messagesTextArea.value+="Server connected...."+"\n";
}
function processMessage(message){
messagesTextArea.value+="Received from server:...."+message.data+"\n";
}

Unable to update value of component which is bound to bean

I am trying to create a socket client with a web UI by JSF. In this application, the client is connecting to the server, sends the message to the server, receives the message from the server and displays it on the JSF page.
I managed to connect to the socket server send message and receive message. I am unable to show the message from server in the browser screen. When I print in the console, it displays correct.
My jsf code is:
<f:view>
<h:form binding="#{jsfSocketClient.form}">
<a4j:keepAlive beanName="jsfSocketClient"/>
<h:outputText binding="#{jsfSocketClient.outputMessageBinding}"/>
<br/>
<h:inputText value="#{jsfSocketClient.inputFromUser}"/>
<br/>
<h:commandButton action="#{jsfSocketClient.sendMessage}" value="Send"/>
</h:form>
</f:view>
And my java code is:
public HtmlForm getForm() {
try {
socket = new Socket("192.168.1.115", 4444);
response = "Connection Success";
outputMessageBinding.setValue("Connection Success");
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
response = "You must first start the server application (YourServer.java) at the command prompt.";
outputMessageBinding.setValue(response);
}
return form;
}
public String sendMessage() {
outputMessageBinding.setValue("");
try {
//String str = "Hello!\n";
out.println(getInputFromUser());
try {
String line = in.readLine();
outputMessageBinding.setValue(line);
System.out.println("Text received :" + line);
} catch (IOException e) {
outputMessageBinding.setValue(e.getMessage());
System.out.println("Read failed");
System.exit(1);
}
//response = result.toString();
if (getInputFromUser().equalsIgnoreCase("bye")) {
socket.close();
}
} catch(Exception e) {
outputMessageBinding.setValue(e.getMessage());
e.printStackTrace();
}
return "";
}
When I load the jsf page, if the server is connected 'Connection Success' is shown correctly, if not connected the error message is shown correctly. When I try to display the server message in the screen, it is not getting displayed. How can I fix this?
Update
If I create new outputtext component and set the message from server as its value, then the Server message is getting displayed correctly. I want to know why binding did not work in my case?
Opening new sockets from a JSF/Webpage is a major anti-pattern. Why do you want to do this?
Are you aware of all the implications/limitations/risks/problems?
Update:
Creating sockets from web pages has several implications with regards to performance and security.
If you just want to practice Java sockets the simplest way is with command line clients.
http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html
No need to add extra complexity with JSF or any other web technology. You can have sockets without a web server. (In fact sockets existed long before http).

Categories