I am working on a problem where i have to send data from PC application (written in java) to android application (java).
It is a cash register application that need to display bill details on android app. While there is no bill, android app need to display something else (pictures etc.) Cash register application already exists, it is desktop PC software.
What is the best way to do this?
It is currently done with writing and reading from a file, but i would like to do it in a better way.
I start to work with sockets, where android app is a servers waiting for cash register application on PC to start connection. When this happen, connection is open and cash register is sending JSON Strings until the end of a bill.
I chose android to be server because of the possibility that one cash register have more than one android connected so it can display bill details on more than one "screen", and also to make possible that android app keep specific port always open and listen on it for client.
Is this a good way to do it? I just read about possibility that socket connection may die during the non-use period and that could be hardware issue. I read also about RMI java and don't know if i should go that way. I have never worked on communication between devices so i appreciate every suggestion.
I did as suggested and changed logic. I made PC server, and android client.
This is the code for test server app if anyone needs it. It is simple server that send messages entered in terminal to client over chosen port.
public static void main(String[] args) {
while (true) {
try {
ServerSocket serverSocket = new ServerSocket(12345);
Socket socket = serverSocket.accept();
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
while (true) {
if (socket.isConnected()) {
System.out.println("connected");
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = bufferedReader.readLine();
System.out.println(name);
dataOutputStream.writeUTF(name);
if (false) break;
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I am porting an Android application to iOS platform. This is a app that uses TCP socket programming to communicate with an external ESP8266 device. To debug code I wrote a code in Java using IntelliJ IDE to act as server and Xcode simulator is acting as the server.
try {
ServerSocket serverSocket=new ServerSocket(1234);
System.out.println("Server Started");
System.out.println(serverSocket.getInetAddress());
Socket socket=serverSocket.accept();
System.out.println("Client Accepted");
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
System.out.println("Got: " +bufferedReader.readLine());
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
this is the code for Server using Java.
switch client.connect(timeout: 10) {
case .success:
toggleSwitch.isEnabled=true
connectBtn.isEnabled=false
upArrow.isEnabled=true
downArrow.isEnabled=true
default:
let alert = UIAlertController(title: "Connection Failed.", message: "SST Device is not available", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
self.present(alert, animated: true, completion: nil)
}
Above is the part where iOS device connect with the server.
resistanceValueInt-=1
let x=client.send(string:"\(-1)")
this is where the client sends data to the server. resistanceValueInt is starting at 0 when the app loads. And increment in each button press.
My question is connection with server established immediately. Though the increments and decrements to the values using buttons won't show up immediately. Simulator needs to quit in order to show the result in the Server Console.
Why simulator needs to be closed in order to deliver the data? How should I fix it?
in the server side i used bufferedReader.readLine() to read from the client.
Though in the swift code client writes data to stream by client.send("\(+1)"). this do not attach new line character to the stream. So that Java server do not know data is fully came through or not because there is no new line character.
So client.send("\(+1)\n") is used. Now Server knows data is came through correctly. So that it prints the required output in the console.
At this point, I am testing a webserver client/host system to be run on my raspberry pi (host) and on my pc (client). The basic idea is that every 5 seconds, the client on my pc sends a message to the host located at "192.168.0.11" at port 7051. It processes it and sends a message back to my pc.
For this I am using the following client code:
public static String getData() throws Exception {
try {
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
socket.setReuseAddress(true);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int msg = 71;
out.write("TEALBEE_CUR:" + msg);
out.flush();
String input;
String data = "";
while ((input = in.readLine()) != null) {
data += input;
}
socket.close();
return data;
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
The problem here is that while data-flow is consistent and can run for at least a week; I lost use of other sockets connections on my pc, namely my Kodi remote control (this is media centre which I can control through a socket connection on my smartphone). My pc at address "192.168.0.37" accepts connections at port 193 for Kodi but after running the Java client for some time and sending a lot of requests to the server, I notice that the remote cannot connect anymore to my PC.
I thought that this might be the case because the sockets cannot be reused and after a single use the socket becomes unusable. This does seem to be the case as my host detects a different socket port for each request.
I tried to solve this by adding the code socket.setReuseAddress(true) and properly closing the socket after each message, but the problem still occurs.
How can I fix this properly (if possible only use one client socket and close this properly so it can be used again the next time).
EDIT: also important to note I can access 192.168.0.37:193 from my PC, but not from my smartphone when the socket connection cannot be established. Yes I am sure that the PC and smartphone and RPI are on the same network and without the client program running I CAN access 192.168.0.37:193 from my smartphone.
i have an application on my android device like "A" and same application installed on the other android device like "B", now i want to send data from app "A" to app "B" using WIFI service. so please suggest me how can i implement this feature.
i tried many times to get help from google but all is vain.
it is possible from WIFI direct or NFC.
You could use a simple p2p architecture.
You will need to use this, this and a pair of streams that works with the kind of data you need to send, like this.
On sender side:
Socket s = new Socket(IP,PORT);
s.connect();
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.write("hello".toByteArray());
Then on receiver side:
ServerSocket ss = new ServerSocket(PORT);
Socket s = ss.accept(); //This call will block execution, use separate thread
DataInputStream dis = new DataInputStream(s.getInputStream);
byte[] data = dis.read();
With this you can send and receive bytes, just use the stream that works with your data type.
Of course, once connection is established, both clients could send/write, just make the appropiate Input/Output Stream.
Hope this helps.
I'm trying to write an android app that interacts with a server. I'm trying now to write the server side with sockets. I created an instance of ec2 and ran it. I connected to it with putty and ran a simple "hello world" java program. Now I'm trying to run a server which use a socket, but I get this as the server socket: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=5667].
This is my code, very basic so far:
public class EchoServer {
public static void main(String[] args) throws IOException {
int portNumber = 5667;
System.out.println("server socket main");
try (ServerSocket serverSocket = new ServerSocket(portNumber);
) {
System.out.println(serverSocket.toString());
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
What should I do to run the server so I could connect to it via my andriod device?
Thanks!
You are on the right track. 0.0.0.0 simply means:
A way to specify "any IPv4-interface at all". It is used in this way when configuring servers (i.e. when binding listening sockets).
Next, your server will need to listen for incoming connections by using SocketServer.accept().
And then of course you'll want to receive and send data on the socket. This tutorial should help.
Finally, if you plan on serving multiple clients simultaneously with your server, you will want to consider concurrency and scalability, and perhaps consider using a framework like Netty.
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?