public class Client {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Socket sock = new Socket();
sock.connect(new InetSocketAddress(InetAddress.getLocalHost(), 43594));
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());
out.writeByte(255);
out.writeLong(133713371337L);
System.out.println("Response: " + in.readByte() + ", " + in.readLong());
sock.close();
}
and the PHP server meant to read and write back to the java client:
<?php
require 'Stream.php';
$stream = new Stream();
$address = '127.0.0.1';
$port = 43594;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, 0, $port) or die('Could not bind to address');
socket_listen($sock);
echo "Server listening on port " . $port . "...";
$client = socket_accept($sock);
$data = socket_read($client, 1, PHP_BINARY_READ);
$byte_array = unpack('C*', $data);
$stream->setStream($byte_array);
$b2 = $stream->readUnsignedByte();
$l1 = socket_read($client, $stream->readQWord());
echo $b1 . " " . $l1;
socket_write($client, 0);
socket_write($client, $stream->writeQWord(2148000000));
The stream class being used: http://pastebin.com/p1vc9aPG
I'm trying to write a client in java that contacts, sends and reads data to/from the server. The server is written in PHP and ran via cli, while the client is written in java. Please help if you can, there probably aren't many people who can help with this issue.
The protocol is already established and I'm just trying to implement it in PHP. I can't seem to read/write back to the java client from the PHP page.
The client side in Java is defined how I want it to be. What I'm looking for is the equivalent server in PHP and I can't seem to get it to work.
I've actually written this the other way around, the client was a PHP web app and the server was a java daemon under jsvc.
The first consideration should be defining a transfer protocol, since the types and object representations of the two languages are different and they might be running on hardware with different numeric representations. I'd recommend JSON or XML.
After that your server probably needs to be able to handle multiple connections, so threading or non-blocking socket I/O will be needed.
First, you should call .flush() after you write to the socket in your Java code. The data won't get sent to the server otherwise.
Then, communications between network endpoints is just about agreement on the protocol used. There is nothing language specific here...
Related
I am currently working under proxy server (the core was taken from here https://resources.oreilly.com/examples/9781565923713/blob/master/SimpleProxyServer.java)
But, this example uses launch parameters, when I want to pass host directly from the client.
Client is a HTTP connection like that
final HttpURLConnection conn = (HttpURLConnection) new URL("http://www.google.com")
.openConnection(
new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7901)));
conn.connect();
System.out.println(conn.getResponseCode());
My initial idea was to read client's request, store it as String (or byty[]), fetch header's "Host:" parameter and pass it to server.
However, SimpleProxyServer.java uses while((bytes_read = from_client.read(request)) != -1) in the Thread that sends data to server, and code hangs on that moment if I read InputSream to get host before this t thread was started.
I am talking about something like this
InputStreamReader from_client_reader = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(from_client_reader);
String line = reader.readLine();
while (!line.isEmpty()) {
line = reader.readLine();
if (line.contains("Host: ")) {
host = line.substring(line.indexOf("Host: ") + 6,
line.length()).trim().replace("www.", "");
}
}
Right before creating of the connection try { server = new Socket(host, remoteport); }
The question is: "Is there other ways on how to pass parameters to Socket or how to create Proxy server that launches Socket using request parameters from the client?"
Well, if someone ever wonders, I decided to create another small Socket server that listens for commands from client, and launches process (java -jar ProxyServer.jar <...>) through Runtime. Also, kills this process if necessary.
Basically, client has to send two requests: one to setup Proxy server, another to connect to the proxy server.
I am sure there is a better solution for this, however, this one suits me.
I have a Python server that listens for json requests. The "receiving" section of the code looks like this:
while True:
next_message = conn.recv(1024)
response = Foo.do_some_stuff(next_message)
conn.send(response)
I built a Sinatra application that uses the Python API.
client = TCPSocket.new("localhost", 5000)
client.puts("foobar")
response = client.gets
All of the above code functions perfectly. Now, I'm doing something similar with some Java code.
Socket client = new Socket("localhost", 5000);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(new client.getOutputStream(), true);
out.println("foobar");
String response = in.readLine();
The problem is that this code works for the first request, but on subsequent requests the Python server hangs, still waiting for the message. My question is what is the Ruby implementation of output stream appending to the message to signal the message's end that the Java implementation isn't?
Relevant details:
I'm using the Google Gson package in the Java code to create Json objects that I send to the Python server.
I'm using auto-flush on the PrintWriter.
I read that perhaps subsequent requests alter the size of the data being sent to the Python server - because of the underlying TCP protocol, and that the Python socket will keep listening until the connection ends or it's read 1024 bytes. This would make sense, except that the Ruby implementation works perfectly.
I've been digging through Java, Python, and Ruby docs for the past two days trying to figure this out. Any help would be greatly appreciated.
I would like to create a program that will emulate a device connected to the network and send signals through a specific port.
The device is connected to the network and sends data through a port. On the server(or computer) I have running the CPR Manager v.4.3.0.1 from Lantronix that will associate the IP:PORT to a virtual COM port on the computer. I have a java program that listens to the COM ports and performs an action, this works great with the device.
I tried writing a java app using the Socket class to perform the connection but it was un successful, on the CPR side it only registers a Disconnect when the very first line is executed:
Socket socket = new Socket("192.168.1.160", 8888);
I also tried it using the UDP method and no message whats so ever is recorded.
Any help would be greatly appreciated. Also if there is no possible solution for Java then any other language would do fine.
EDIT:
Here is the Java code where I am attempting to send the data
public static void main(String[] args){
try{
Socket socket = new Socket("192.168.1.160", 8888);
if(socket.isConnected()){
System.out.println("It is connected.");
socket.setKeepAlive(true);
System.out.println(socket.isBound());
}else{
System.out.println("It is not connected.");
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String msg = "32";
for(int i = 0; i < 50; i++){
out.println(msg);
}
//Receive a reversed message
msg = in.readLine();
System.out.println("Server : " + msg);
}catch(Exception ioe){
ioe.printStackTrace();
}
}
Thanks.
Update
I got in contact with some people of the devices and they showed me that there is a way to communicate straight via a TCP/IP connection sending there ASCII Command Protocols. This would allow more in depth control at every level.
So, now I am writing a java program that can communicate using these protocols.
Because, I am not using a comm port anymore I am tying to emulate the baud rate, data bits, stop bit stuff. I will post when I have some that works.
Thanks for all the help.
if the product you are using is forwarding the traffic to a COM port should you be listening on the COM port not on a network connection. Sockets are for network traffic. A quick google search resulted this for me.
How to send data to COM PORT using JAVA?
Maybe that will help?
I have written a client side java application which communicates through http to a php server. I need to implement a listener on the java (client) side to respond to requests made by the php server. Currently, the java apps are hitting a text file on the server that is updated every minute.
This has worked ok, but now the number of client java apps is rising and this primitive system is starting to break down.
What is the best way to change this? I tried a java ServerSocket listener on the java client app, but can't get that to work. I am having trouble completing the communication. All examples on the web use localhost as ip address example, and my php server is remote hosted.
Do I need to get the ip address of the client machine and send that to the php server so php will know where to send the message? Here is the java code... This is all over the web...
public class MyJavaServer
{
public static void main(String[] args)
{
int port = 4444;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try
{
System.out.println("listen");
listenSock = new ServerSocket(port);
while (true)
{
sock = listenSock.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null)
{
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
}
catch (IOException ex)
{
System.out.println(ex);
}
}
}
... and here is the php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "ip address(not sure here)"; //the ip of the remote machine(of the client java app's computer???
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT)
or die("error: could not connect to host\n");
$text = "Hello, Java!\n"; //the text we want to send to the server
socket_write($sock, $text . "\n", strlen($text) + 1)
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ)
or die("error: failed to read from socket\n");
echo $reply;
This simply does not work. The java app listens, but the php script never connects.
Also, is this the best method for my needs??
Thanks.
The code you include works if the php server machine could connect to the java client machine. In your case that this is all over the web, it means that the java client machine should have an IP that are accessible to public. Once you have it, assign that IP to $HOST, then the code will runs fine.
Assuming that no client can have a public IP, I think the best method is to make your java client talk to your PHP Server in request-reply manner using HTTP request. The java client, acting like a web browser, send a HTTP request and receive HTTP reply that contains data needed by your java client. And when the client numbers rise to a level that you PHP server cannot handle, you could scale it up. Although I haven't had the experience myself, scaling up a PHP server is not uncommon these days.
I'm trying some multiplayer game ideas out at the moment and am trying to create a Java application to serve a web browser based multiplayer game.
My development environment is Eclipse on the main machine, and notepad + Google Chrome on this laptop.
I'm creating the websocket using javascript at the client end, and using the java.net.Socket at the server end.
I've managed to get a connection acknowledged at both ends, but can't seem to send or recieve any data between them without the client closing the connection (doesn't even error; just seems to freak out at something and call socket.close).
Does anyone have any ideas?
Here's some code:
Client:
<script type="text/javascript">
var socket;
function init() {
socket = new WebSocket("ws://192.168.0.3:10000");
socket.onopen = function() { alert('OPEN: ' + socket.readyState); }
socket.onmessage = function (msg) { alert('DATA: ' + msg.data); }
socket.onerror = function (msg) { alert('DATA: ' + msg.data); }
socket.onclose = function () { alert('CLOSED: ' + socket.readyState); }
}
function onClick() {
socket.send("YAY!");
}
</script>
Server:
public static void main(String args[])
{
System.out.printLn("Websocket server test");
ServerSocket connectSocket = null;
try
{
Socket clientSocket;
connectSocket = new ServerSocket(10000);
System.out.printLn("Waiting for connection...");
clientSocket = connectSocket.accept();
System.out.printLn("Got one!");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
for(int i=0;i<100;i++) //Shit but easy
{
String data = in.readLine();
System.out.printLn("Got data: " + data);
out.printLn("YAY!");
}
}
catch (IOException e)
{
System.out.printLn("You fail: " + e.getMessage());
}
System.out.printLn("Finished!");
}
Rather than going the painful way of implementing the spec in Java, I'd suggest that you use an existing solution like jWebSocket.
Also if you don't mind leaving Java land, I'd also suggest that you take a look at Node.js for your Server.
Doing both Server and Client in JavaScript will save you lots of time and lots of Code, especially since JSON just doesn't fit that well into static land. Also creating multiplayer servers in Node.js is trivial, since the event based, single threaded model fits the whole thing pretty well.
More information on WebSocket can be found in the FAQ. In case you want to get started with Node.js take a look at the TagWiki.
shameless plug follows
For two multiplayer games that were written using Node.js take a look at my GitHub page.
Try this lib - https://github.com/mrniko/netty-socketio
Based on high performance socket lib Netty. It supports latest protocol of Socket.IO server. Several transports including websocket.
On web side use Socket.IO client javascript lib:
<script type="text/javascript">
var socket = io.connect('http://localhost:81', {
'transports' : [ 'websocket' ],
'reconnection delay' : 2000,
'force new connection' : true
});
socket.on('message', function(data) {
// here is your handler on messages from server
});
// send object to server
var obj = ...
socket.json.send(obj);
</script>
I would suggest our high level solution: Bristleback Server. It contains both server and client, you can choose from several existing low level WebSocket engines (like Jetty, Netty or Tomcat), developing with Bristleback is extremally fast and easy. However, it is still Beta and we are working hard to release a final 1.0.0 version. If you use Maven, we have provided an archetype with ready to use web application.
I am one of the co-creators of Bristleback Server.
As no one yet really answered your question: the reason it does not work, is because you are not implementing the websocket specification. It takes of lot more work to setup a proper websocket connection than just opening a socket, as the websocket connection setup starts with a HTTP upgrade request. Your client is closing the connection, because it does not receive a positive answer on the upgrade request to start with.
I can't help you with sockets, but can i suggest you to use RMI technology? I'm trying to make a multiplayer rpg in java, and i'm using remote method invocation between server and client (it is possible also call-back the client from the server). It's really easy use it, but it uses TCP instead of UDP. In LAN experience there is no lag, on internet I have not tried yet. However, if your game tolerates just a bit retard between request and response, there is no problem.
This is the link of my project, Client and Server classes may be useful for you.