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?
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 am currently trying to make an application that will send messages to a server using one port, but will receive messages on another port. However, based on tutorials I have followed, it looks like the act of connecting to the server is where ports come into play and my client is receiving and sending messages on the same port. How do I make it so it sends on one port but receives on the other?
Here is the code that I think is relevant from the client side (I put some stuff that seems unrelated because I think they are things that would be altered by receiving on one port but sending on another, and ignore the comment about replacing inetaddress, that is just me working on implementing this in a gui):
public void startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeStuff();
}
}
//connect to server
private void connectToServer() throws IOException{
showMessage("Attempting connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 480);//replace serverIP with ipTextField.getText or set serverIP to equal ipTextField.getText? Same with port number.
showMessage("Connected to: " + connection.getInetAddress().getHostName() );
}
//set up streams to send and receive messages
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are good! \n");
}
//while talking with server
private void whileChatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classNotfoundException){
showMessage("\n Don't know that object type");
}
}while(!message.equals("SERVER - END"));
}
//send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
messageWindow.append("\n something messed up ");
}
}
//change/update message window
private void showMessage(final String m){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
messageWindow.append(m);
}
}
);
}
EDIT/UPDATE: To help clarify some things, here is some more information. The device that sends the first message is connected to a sensor, and it sends information when that sensor detects something to the other device. The receiving device sends a message back on a different port telling the original sending device how to respond. Lets name these two devices the "reporter-action taker" and the "decision maker-commander".
If you want to use TCP/IP sockets you can't use a a socket to send and another to read. That's not what they are for.
If you use a centralized distributed algorithm (server/client communication) you have to set the server to listen on a single socket port with the ServerSocket class: then the server tries to accept clients through that socket.
Example:
ServerSocket listener = new ServerSocket(Port)
While (true) {
new Clienthandler(listener.accept());
}
The server will listen on that port, and when a client tries to connect to that port if it is accepted the server launches its handler. On this handler constructor the Socket object used on the client is received on an argument and can then be used to get the writers and the readers. The reader on this handler class will be the writer on the client class and vice-versa, maybe that's what you were looking for.
Your question about using two ports in this manner is a bit strange. You state that you have a client and a server and that they should communicate on different ports.
Just to clarify picture the server as a hanging rack for jackets with several hooks in a row. Each port the server listened on represents a hook. When it comes to the client server relationship the client or jacket knows where to find its hook, however the hook is blind and have no idea where to find jackets.
Now, the client selects a port or a hook and connects to it. The connection is like a pipeline with two pipes. One for the client to deliver data to the server with and the other to send data from the server back to the client. When the connection is established data can be transferred both ways. This means that we only need one port open on the server to send data both from the client to the server and in the opposite direction.
The reason for only having one open port open on the server for the clients to connect to is that holding an open port for connections is hard to do on a regular client computer. The normal desktop user will be behind several firewalls blocking incoming connections. If that wasn't the case the client would probably be hacked senseless from malicious viruses.
Moving on with the two port solution we could not call this a client server connection per say. It would be more like a peer to peer connection or something like that. But if this is what you want to do, the application connecting first would have to start by telling the other application what ip and port to use for connecting back, it should probably also want to give some kind of token that are to be used to pair the new incoming connection when connecting back.
You should take note that making such an implementation is not a good idea most of the time as it complicates things a whole lot for simple data transfer between a client and server application.
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.
The app uses sockets to connect to the computer but will only connect if the computer is connected to the network by an ethernet cable. I've tried disabling the firewalls but that makes no difference.
The code for the server on the computer:
int port = 7936;
while(true){
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client ...");
Socket client = server.accept();
System.out.println("Client from "+client.getInetAddress()+" connected");
InputStream in = client.getInputStream();
and the code for the client on the app:
Socket socket = new Socket(address,7936);
OutputStream out = socket.getOutputStream();
String action = "2";
byte[] actByte = action.getBytes();
out.write(actByte);
socket.close();
Address is defined by user input and all the permissions needed have been set in the manifest xml file.
Thanks for the help.
Edit
Sorry for the delay in responding to the answers given. I have since been able to try the program on a different network and it works with the computer connected wirelessly so it looks like the issue was with the network rather than the code.
Thanks to everyone for answering and I'm sorry it took me so long to respond.
As others have mentioned, more information is needed. When you disconnect the computer from the wired connection, I assume it is switching over to wifi and you've verified that you are online. Your computer is likely to get a different IP address if you're DHCP as the interface changed and so wouldn't the MAC address.
Check the address on the computer and verify you have the right address.
What I'm thinking is that the socket is not bound to the IP address you think it is. You may wish to try using the TcpListener class, that way you can bind it to the IP address (network adapter) you want.
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.