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.
Related
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();
}
}
}
I have made a simple java chat program that will have 1 server and 1 client. It works fine on windows, it can chat with each other within LAN.
But when I try it on Mac computer, it doesn't work. In the server program, if it works properly, it should freeze when I press the start button, and wait for client to join. But in Mac, it does nothing when I press start button. The program doesn't freeze, it's like clicking on a non-coded button. The client in Mac cannot join the server too (server hosted in Windows).
On Windows: Start server --> freeze(wait for client) --> Client joined --> able to chat
On Mac: Start server --> not freeze, like click on normal button --> Client clicked join --> nothing happens
In the Start Server button:
private void startsvbtnActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
server = new ServerSocket(7430);
client = server.accept();
System.out.println("Client request accepted: "+client.getOutputStream());
dos = new DataOutputStream(client.getOutputStream());
dis = new DataInputStream(client.getInputStream());
ReceiveMessage serverThread = new ReceiveMessage(dis,textarea);
serverThread.start();
} catch (IOException ex) {
System.out.println("No client available");
}
}
You're checking only IOException, as per doc there could be other exceptions. Catch all and print stacktrace.
http://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html#accept--
catch(Exception e){
e.printStackTrace();
}
Because your button doesn't freeze I would say that the problem is an exception is being thrown, hence your ActionListener returning virtually immediately.
Check your log file to see if your log message System.out.println("No client available"); is there. Also at the very least modify this code to output the stack trace, as I would bet that you cannot bind to the port specified here:
server = new ServerSocket(7430);
I am writing an application that streams data that clients can then listen to and receive. However I am running into an issue with closing a socket when a client is no longer listening.
What I do is create a ServerSocket, when then waits for a connection and once it is connected, I start streaming the data. However, once the client is no longer connected, I am stuck in a loop of streaming and cannot tell if anyone is listening. Is there a way around this?
try {
serverSocket = new ServerSocket(STREAM_PORT);
Socket clientSocket = serverSocket.accept();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
pw.println("some data");
}
} catch (SocketException e) {
// Never occurs when client disconnects
} catch (IOException e) {
// Never occurs when client disconnects
}
I have tried using socket.isClosed(), but it always returns false. Am I approaching this from the wrong angle, or is there a way to do it. I would ideally not want the client to have to send the server a "end" command.
EDIT: Edited to reflect what current code I am running after #Rod_Algonquin suggestion
As you are using PrintWriter, which swallows I/O exceptions, you need to call checkError() after each write to see if an error has occurred.
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 am using the following code to connect my client to the server. The problem is this doesn't terminate and I am unable to start a new activity after this one.
I think the problem is either I don't close the socket or the thread doesn't terminate.
I start the thread in onCreate()
cThread = new Thread(new ClientThread());
cThread.start();
And here is my Runnable
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, 8080);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println(serverIpAddress);
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error while sending", e);
}
connected = false;
}
//socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error while connecting", e);
connected = false;
}
}
}
Your program is quite useless. Assuming the socket is estabilished, the while loop is executed only once because, at the end of the first iteration, you set connected to false, thus disabling any further cycle. You don't flush your buffered output to ensure it's written, and you don't even read from the socket, so I wonder what your custom protocol looks like... At this moment, all your program does is simply writing a string to a server, then exiting. We can't even tell why you are not able to start a new activity, because in the supplied code there is nothing preventing you from doing so.
There are basically two kinds of TCP protocols
Request-response based (like HTTP, not suitable for a chat program). The client estabilishes a connection, makes a request, reads the response, makes another request, reads the new response and so on, till the client has finished its job. A graphical client will need 2 threads at least: one for the UI update and the other for network communication.
Client and server both send messages at random times. This leverages the full-duplex capability of socket communication, however you'll need at least three threads in a GUI program: one for the UI, one blocked on the socket's input stream, and one for writing. Things get quite messy because you'll likely share streams and have to synchronize by hand.
If this is yet another chat program, I'd suggest not to design your own TCP protocol, and start with a standard technology like WebSockets. There are Java clients available, and you may test your server simply with a bit of Javascript in your browser, and there are even more choices on the server side (Socket.IO - for a JS solution, Jetty, Glassfish, ...).
After you get some experience and become acquainted with the job, you may try to design your own custom TCP protocol. By the time, you'll have learned at least the basics of sockets, threads and Android programming.
BTW, you may want to take a look at the Service API for background tasks which don't require user interaction.