Sending ASCII and protocol commands to server - java

I managed to setup a client and server connection using Java socket. After checking the connection had been establish, I tried sending Protocol commands that are provided by the SDK from the server and I'm using a JButton to execute the commands.
Examples of the commands are play, stop and ping the server.
The code below shows how I setup the connection and send the protocol commands
public void socket1()
{
Socket MyClient;
try {
MyClient = new Socket("192.168.10.61",9993);
os = new DataOutputStream(MyClient.getOutputStream());
is = new DataInputStream(MyClient.getInputStream());
lblerror.setText("Connected");
MyClient.getOutputStream().write("play".getBytes("US-ASCII"));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
lblerror.setText("Don't know about host: hostname");
} catch (IOException e) {
// TODO Auto-generated catch block
lblerror.setText("Couldn't get I/O for the connection to: hostname");
}
}
After pressing the button on the GUI, The server did not response to the command 'play' and there is no error.

As Scarry Wombat wrote, use os.write()
But instead of .write() use .writeBytes(),
because you want to send a byte array(?). Alternatively you could send a String with UTF-encoding by using .writeUTF()

Related

android signalR hubconnection application negotiation failed with server

hi i'm new in android developing and i want to write an application which use signalR java-client. in first step i did the answer of this and here is my client code:
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "localhost";
HubConnection connection = new HubConnection( host);
HubProxy hub = connection.createHubProxy("HubConnectionAPI");
SignalRFuture<Void> awaitConnection = connection.start(new LongPollingTransport(connection.getLogger()));
try {
awaitConnection.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
hub.subscribe(this);
try {
hub.invoke("DisplayMessageAll", "message from android client").get();
System.out.println("sent!!!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
and u can download the server code from here
i have following error with awaitConnection.get();
error:
W/System.err: java.util.concurrent.ExecutionException: microsoft.aspnet.signalr.client.transport.NegotiationException: There was a problem in the negotiation with the server
i also have this error:
Caused by: microsoft.aspnet.signalr.client.http.InvalidHttpStatusCodeException:Invalid status code: 404
can anyone please help me? i searched a lot but i didn't found anything helpful for me
EDIT:
clients can access the hub via this but how can i implement on android so my application can connect?
this is the log file on server:
2015-11-11 09:05:08 10.2.0.18 GET /signalr/negotiate clientProtocol=1.3&connectionData=%5B%7B%22name%22%3A%22hubconnectionapi%22%7D%5D 80 - 10.2.0.253 SignalR+(lang=Java;+os=android;+version=2.0) - 404 0 2 3
changed the String host = "localhost";
to String host = "localhost/signalr";
localhost didn't work for me, i had to deploy the asp.net web application on IIS, allow the port in Firewall inbound rules and put it in signalr config in android.. hope this helps someone... Cheers!

Reading Data from Bluetooth Data Transfer on Android

I am looking to get/read the Data I passed after I connected a couple of Android Devices, so far I pair, connect and transmit the information between them, but not sure how to implement the reading part, here I am not sure if I should use createRfcommSocketToServiceRecord or listenUsingRfcommWithServiceRecord to create the reading socket for this purpose.
I have two screens, one where the user push a button and transmit the info and the other where the receiver press another button and read the data, I wonder if the sync is incorrect and after I push the "send" button and then the "read" button the connection is unavailable or if this implementation is just not recomendable all together.
These are my two attempts:
Attempt 1:
//Executed after the user press the read data button
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(device.getName(),uuid);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
BluetoothSocket clientSocket = serverSocket.accept();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
Attempt 2:
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {
try{
BluetoothServerSocket clientSocket = device.createRfcommSocketToServiceRecord(uuid);
//clientSocket without method and invoke is not working either
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
clientSocket = (BluetoothSocket) m.invoke(device, 1);
//Here is where I get the error:
//io to Server Socket JSR82 Connection is not created, failed or aborted
clientSocket.connect();
// Start listening for messages.
StringBuilder incoming = new StringBuilder();
listenForMessages(clientSocket, incoming);
// Add a reference to the socket used to send messages.
transferSocket = clientSocket;
} catch (IOException ioe) {
this.printToast("Excep io toServerSocket:" + ioe.getMessage());
} catch (Exception e) {
this.printToast("Excep toServerSocket:" + e.getMessage());
}
}
On serverSocket.accept() or clientSocket.connect() I get the exception:
Connection is not created, failed or aborted
I would appreciate if anyone could guide me towards getting the data reading part working. Thanks.
Take a look at Android's BluetoothChat example included with the Android SDK. I think it does exactly what you want.
$ANDROID_SDK/samples/android-19/legacy/BluetoothChat/src/com/example/android/BluetoothChat
Read the managing the connection part.
Its clearly written in the documentation how to exchange (read/write) info between devices through Bluetooth. http://developer.android.com/guide/topics/connectivity/bluetooth.html

Client-Server Program, can connect from Java client but not from Android

I have a working Java client/server program which is very straightforward and basic. This works fine. However, I am now trying to write an Android client, and I have been unable to connect to the server from my android client. I am using almost identical code for the android networking code as I use for the normal client. My android code is simple, all it does is starts this thread from onCreate:
private int serverPort = 8889;
private String serverIP = "192.168.5.230";
private Socket socket = null;
private Thread clientThread = new Thread("ClientThread") {
#Override
public void run() {
try {
socket = new Socket();
socket.connect(new InetSocketAddress(serverIP, serverPort), 1000);
DataInputStream din = new DataInputStream( socket.getInputStream());
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
while (true) {
String message = din.readUTF();
setPicture("picture1");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
The port is the correct port my server is running on, as is the ip address (which I got from ifconfig since I know you cannot use localhost). When I run my normal pc client with the same port and IP address, the connection goes through. But when I run this code on my android device, the socket timesout when I try to connect.
Does anyone have any suggestions for where I am going wrong?
Double check that you added the permission requirement in the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
But, possibly more importantly, 192.168.x.x is a local or non-routable network so you need to be on the same network, or one that knows how to reach the 192.168.5.230 address. You say that it doesn't work when you try it on your device -- are you running on local wifi when you run or are you on your mobile network? If you're on mobile, try it from wifi.

java RMI + source hitting server is from internet or from intranet

In java RMI i am building a chat application. But i am not able to figure out a way to find out, whether the IP which is hitting my server is from my internal organization network(INTRANET) or from external world(INTERNET).
Right now i am using
try {
System.setProperty("java.rmi.server.hostname",InetAddress.getLocalHost().getHostAddress());
Registry statusRegistry = LocateRegistry.createRegistry(ChatConstants.statusPort);
ChatInterface chat = new ChatImpl(ChatConstants.statusPort) ;
statusRegistry.rebind("statusconnection",chat);
System.out.println("RMIStatusConnection Server is started...");
} catch (RemoteException e) {
System.out.println("RMIStatusConnection failed...");
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Try RemoteServer.getClientHost(), but it may only provide the address of the nearest NAT device.
NB there's not much point in setting java.rmi.server.hostname like that. That's the default. You only need to set it if there's something wrong with the default setting.

How to read response from remote server using Java Sockets

Part of a Java program I'm creating needs to talk to a service on a remote machine. That remote machine is running a service (written in Delphi I believe) on a Windows platform.
I need to connect to that machine, send command strings and receive (String) responses.
If I connect using Linux CLI telnet session I get responses as expected:
[dafoot#bigfoot ~]$ telnet [host IP] [host port]
Trying [host IP]...
Connected to [host IP].
Escape character is '^]'.
Welcome to MidWare server
ping
200 OK
ProcessDownload 4
200 OK
In the above the lines 'ping' and 'ProcessDownload 4' are me typing in the terminal, other lines are responses from remote system.
I created a Main in my Java class that will do the work to call the appropriate methods to try and test this (I've left out irrelevant stuff):
public class DownloadService {
Socket _socket = null; // socket representing connecton to remote machine
PrintWriter _send = null; // write to this to send data to remote server
BufferedReader _receive = null; // response from remote server will end up here
public DownloadServiceImpl() {
this.init();
}
public void init() {
int remoteSocketNumber = 1234;
try {
_socket = new Socket("1.2.3.4", remoteSocketNumber);
} catch (IOException e) {
e.printStackTrace();
}
if(_socket !=null) {
try {
_send = new PrintWriter(_socket.getOutputStream(), true);
_receive = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean reprocessDownload(int downloadId) {
String response = null;
this.sendCommandToProcessingEngine("Logon", null);
this.sendCommandToProcessingEngine("ping", null);
this.sendCommandToProcessingEngine("ProcessDownload", Integer.toString(downloadId));
try {
_socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private String sendCommandToProcessingEngine(String command, String param) {
String response = null;
if(!_socket.isConnected()) {
this.init();
}
System.out.println("send '"+command+"("+param+")'");
_send.write(command+" "+param);
try {
response = _receive.readLine();
System.out.println(command+"("+param+"):"+response);
return response;
} catch (IOException e2) {
e2.printStackTrace();
}
return response;
}
public static void main(String[] args) {
DownloadServiceImpl service = new DownloadServiceImpl();
service.reprocessDownload(0);
}
}
As you will see in the code, there are a couple of sys.outs to indicate when the program is attempting to send/receive data.
The output generated:
send 'Logon(null)'
Logon(null):Welcome to MidWare server
send 'ping(null)'
So Java is connecting to the server ok to get the "Welcome to Midware" message back, but when I try to send a command ('ping') I don't get a response.
So the questions:
- does the Java look about right?
- could problem be related to character encoding (Java -> windows)?
You need to flush the output stream:
_send.write(command+" "+param+"\n"); // Don't forget new line here!
_send.flush();
or, since you create a auto-flushing PrintWriter:
_send.println(command+" "+param);
The latter has the disadvantage that the line end can be \n or \r\n, depending on the system on which your Java VM runs. So I prefer the first solution.

Categories

Resources