We are working for the Camera integration project, we have connected this camera through wifi ( camera act as a server), for interrations camera company provides TCP protocol, I have confused to how to send a request for this. We are trying this in JAVA. Please help us to understand this communication protocols.
Please give a hint or idea to commuction with this device.
We have tried below code and its not worked as expected.
try {
// Create a socket to connect to the server
Socket socket = new Socket("192.168.150.1", 31000);
// Send the payload
OutputStream out = socket.getOutputStream();
out.write(25004);
out.flush();
// Receive the payload
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = in.read(buffer);
String response = new String(buffer, 0, bytesRead);
System.out.println("Response from server: " + response);
// Close the socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Related
Currently trying to send and receive some data via TCP connection using java socket,
creating socket like this:
socket = new Socket();
socket.setSoTimeout(soTimeout > 0 ? soTimeout : DEFAULT_SOCKET_TIMEOUT);
socket.setSendBufferSize(1);
socket.connect(new InetSocketAddress(address, port), connectTimeout > 0 ? connectTimeout : DEFAULT_CONNECT_TIMEOUT);
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
And trying to write data and read response like this:
try {
os = getPort().getOutputStream();
bos = new BufferedOutputStream(os);
is = getPort().getInputStream();
bis = new BufferedInputStream(is);
bos.write(result);
bos.flush();
os.flush();
byte [] reply = new byte[5];
is.read(reply);
} catch (Exception ex) {
throw new RuntimeException("Failed to send data: ", ex.getMessage());
}
field result being byte array, b
Exact same data send via UTP works perfectly, but trying to send it via TCP always ends up with ReadTimeoutException,
there are logs saying that connection is set on the target server, but no logs about received data
Can you maybe give me some hints on what could be the reason?
i'm creating a simple proxy in java.
What i'm doing is use ServerSocket to start it on a specific port and route the requests i've receive to a list of external proxies.
So, teorically i don't need parse the request and response, simply takes bytes recived and route them to the final destination.
My objective is to choose the destination proxy with some application logic.
In order to do this it wold be very usefull to know :
Ip of the client that connect to my proxy
Http response code that i receive from the final proxy
For a "normal" http connection this is possibile. When i read the data i can parse it and get the information i need.
With a https connection, all data are encrypted so i think this is not possibile. Anyone can confirm this and eventually suggest a way to bypass this "problem"?
Here some code as an example :
//start my proxy
ServerSocket ss = new ServerSocket(portNum);
Socket client= ss.accept();
//connection arrived : get pointer to streams
final InputStream from_client = client.getInputStream();
final OutputStream to_client = client.getOutputStream();
//Try to open socket to destination proxy
Socket server = null;
try {
server = new Socket([destination proxy host], [destination proxy port]);
} catch (IOException e) {
PrintWriter out = new PrintWriter(new OutputStreamWriter(to_client));
out.println("Proxy server cannot connect to " + opt.getProxyHost() + ":" + opt.getProxyPort() + ":\n" + e));
out.flush();
client.close();
}
some stuff ...
//get streams from destination
final InputStream from_server = server.getInputStream();
final OutputStream to_server = server.getOutputStream();
//in a separate Thread :
try {
//transfer bytes from client to server ( java >= 9 )
//**NOTE : the https connection is encrypted, is not possibile to parse the request received, just route it**
from_client.transferTo(to_server);
} catch (IOException e) {
//Manage exception
}
The response have the same problem :
int bytes_read;
try {
//**NOTE : the https connection is encrypted, is not possibile to parse the response received, just route it back**
from_server.transferTo(to_client);
} catch (IOException e) {
//Manage exception
}
Thanks
Davide
So, I just learned how to make sockets and all that good stuff in Java, and so my first try got me a message from the client, and then the client crashing. What was supposed to happen was get a message from the client, if that message is equal to this, then send data back. However, the if function for if the message was correct wasn't firing, even though the message was correct.
Even when I remove the if function to check if the string was right or not, the program still freezes up. And by the way, my server is a console application, and my client is a SWT application.
Here's the server code with the removed if function:
try {
System.out.println("Waiting for a connection...");
// Start a server
ServerSocket server = new ServerSocket(3211);
// Listen for anyone at that port
Socket socket = server.accept();
System.out.println("The client has connected!");
// Get the data being sent in
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
DataOutputStream ouputStream = new DataOutputStream(socket.getOutputStream());
// Turn that into UTF-8
String data = inputStream.readUTF();
System.out.println("Received " + data);
ouputStream.writeUTF("Great!");
System.out.println("Awesome!");
socket.close();
inputStream.close();
ouputStream.close;
server.close();
System.out.println("Socket closed\n-----------------------------");
}
catch(IOException e) {
System.out.println(e);
}
And the client (which is fired when a button gets pressed):
try {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnecting to the server...");
Socket socket = new Socket("192.168.1.206", 3211);
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnected to the server!");
DataInputStream input = new DataInputStream(System.in);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("sweet");
String data = input.readUTF();
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nSERVER: " + data);
input.close();
output.close();
socket.close();
}
catch (IOException er) {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\n" + er);
}
As soon as I press the button to try and start the connection (with the server already running), the client instantly freezes. It doesn't even send any of the "connecting to server" kind of stuff.
Any idea what's going wrong, and how to fix this?
Your client is reading from System.in. It should be reading from the socket input stream.
NB You only need to close the outermost output stream of a socket. That flushes it if necessary and closes the input stream and the socket. You're presently not only closing more than necessary but also in the wrong order,
Your socket is unable to send data because you did not called .flush() method on your outputstream reference. Use this one and you don't have to write flush() and close() method explicitely on streams
Server Code
System.out.println("Waiting for a connection...");
// Start a server
try (ServerSocket server = new ServerSocket(3211)) {
// Listen for anyone at that port
try (Socket socket = server.accept()) {
System.out.println("The client has connected!");
// Get the data being sent in
try (DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()))) {
try (DataOutputStream ouputStream = new DataOutputStream(socket.getOutputStream())) {
// Turn that into UTF-8
String data = inputStream.readUTF();
System.out.println("Received " + data);
ouputStream.writeUTF("Great!");
System.out.println("Awesome!");
}
}
}
System.out.println("Socket closed\n-----------------------------");
} catch (IOException e) {
System.out.println(e);
}
Client Code
try {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnecting to the server...");
try (Socket socket = new Socket("127.0.0.1", 3211)) {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnected to the server!");
try (DataInputStream input = new DataInputStream(socket.getInputStream())) {
try (DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
output.writeUTF("sweet");
}
String data = input.readUTF();
System.out.println(String.format("data received from server '%s':\n", data));
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nSERVER: " + data);
}
}
} catch (IOException er) {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\n" + er);
}
Output on Server
Waiting for a connection...
The client has connected!
Received sweet
Awesome!
Socket closed
-----------------------------
Output on Client
data received from server 'Great!':
Now moving to problem in your code.
See the client side code you have written DataInputStream input = new DataInputStream(System.in); instead of DataInputStream input = new DataInputStream(socket.getInputStream())
which causes the failure in receiving message from server
I'm currently working on a project that uses a technique called "domain fronting". In short: it send internet traffic to a CDN (in this case Google) over an encrypted connection, and the CDN then passes back this info to the proxy. This way you can circumvent censorship (as long a the CDN isn't blocked), because the real destination is unknown to a observer. (To read more about domain fronting, here is the original paper) A number of applications like Signal and Tor already use this technique, but there isn't a general use proxy that just proxies a tcp socket through Google to the other end. I decided to go work on that and it's almost finished: the HTTP encoding part and the code at Google's servers is working. The only problem is the real proxying part.
This is the structure of the proxy:
source-->client proxy-->[Google]-->server proxy-->destination
The difference with a general proxy is that HTTP is a request based protocol and thus can't do the asynchronous things normal proxies do. My setup is to make a request from the client once in 100ms to the server sending the bytes the client received to the server. The server reads the bytes from the destination and sends them back to the client. Than the server and client both write their received bytes to the original sockets and another roundtrip starts in 100ms.
Here is my code to this point (I only pasted the relevant part, this code is not domain fronting yet):
Client:
try {
ServerSocket serverSocket = new ServerSocket(8082);
System.out.println("client proxy is listening for connections");
Socket source = serverSocket.accept();
BufferedReader sourceIn = new BufferedReader(new InputStreamReader(source.getInputStream()));
PrintWriter sourceOut = new PrintWriter(source.getOutputStream(), false);
while(true) {
Socket server = new Socket("localhost", 8081);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream(), false);
//read what the source has for the server
System.out.println("start reading source socket");
System.out.println("available: " + source.getInputStream().available());
char[] buffer = new char[15000];
int bytesRead = 0;
if(source.getInputStream().available() != 0) {
bytesRead = sourceIn.read(buffer);
byte[] bytesToSend = new byte[bytesRead];
bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
out.print((byte) 1);
out.print(bytesToSend);
out.flush();
System.out.println("Sent to server: " + new String(bytesToSend) + " bytesRead: " + bytesRead);
} else {
out.print((byte) 0);
out.flush();
System.out.println("Sent to server: nothing");
}
//read what the server has for the source
buffer = new char[15000];
bytesRead = 0;
while((bytesRead = in.read(buffer)) == -1) {
System.out.println("didn't receive any bytes from server");
Thread.sleep(20);
}
byte[] bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
if(bytesToSend[0] == '1') {
sourceOut.print(bytesToSend);
sourceOut.flush();
System.out.println("Sent to source: " + new String(bytesToSend));
} else {
System.out.println("Server has nothing for source; bytesToSend: " + new String(bytesToSend));
}
in.close();
out.close();
server.close();
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
Server:
try {
Socket destination = new Socket("192.168.0.150", 22);
BufferedReader destinationIn = new BufferedReader(new InputStreamReader(destination.getInputStream()));
PrintWriter destinationOut = new PrintWriter(destination.getOutputStream(), false);
ServerSocket server = new ServerSocket(8081);
while(true) {
Socket clientSocket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), false);
System.out.println("received new connection from client");
//read what client has for destination
char[] buffer = new char[15000];
int bytesRead = 0;
while((bytesRead = in.read(buffer)) == -1) {
System.out.println("didn't receive any bytes from client");
Thread.sleep(20);
}
byte[] bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
if(bytesToSend[0] == (byte) 1) {
destinationOut.print(bytesToSend);
destinationOut.flush();
System.out.println("Sent to destination: " + new String(bytesToSend));
} else {
System.out.println("Client has nothing for destination");
}
//read what distination has for client
System.out.println("start reading destination socket");
System.out.println("available: " + destination.getInputStream().available());
buffer = new char[15000];
if(destination.getInputStream().available() != 0) {
bytesRead = destinationIn.read(buffer);
bytesToSend = new byte[bytesRead];
bytesToSend = Arrays.copyOfRange(new String(buffer).getBytes(), 0, bytesRead);
out.print("1");
out.print(new String(bytesToSend));
out.flush();
System.out.println("Sent to client: " + new String(bytesToSend) + " bytesRead: " + bytesRead);
} else {
out.print((byte) 0);
out.flush();
System.out.println("Sent to client: nothing");
}
out.close();
in.close();
clientSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
When I run this code to connect to a SSH server, the SSH client freezes and it seems like the proxy server doesn't respond to the proxy client anymore.
I really hope someone can help me with this, if you need extra info, just let me know! :)
I'm new to Java so I need help please. I'm writing an application that will onClick send a String to Server and Server needs to return an image using socket. So my client side is Android and server side is PC - java.
I think that my server side is ok (because he prints out all the system.out.print commands) but my client side is not good. Please tell my where is my mistake? Thanks!
Here is code of my Server (PC) side (socket is delivered thru function parameter):
try {
dataInputStream = new DataInputStream(socket.getInputStream());
poruka = "" + dataInputStream.readUTF();
System.out.print(poruka);
int bytecount = 2048;
byte[] buf = new byte[bytecount];
OutputStream OUT = socket.getOutputStream();
BufferedOutputStream BuffOUT = new BufferedOutputStream(OUT, bytecount);
FileInputStream in = new FileInputStream("screenShot.jpg");
int i = 0;
while ((i = in.read(buf, 0, bytecount)) != -1) {
BuffOUT.write(buf, 0, i);
System.out.print("check" + buf[0]);
BuffOUT.flush();
}
in.close();
BuffOUT.close();
System.out.print("over");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and here is my Client (Android) side:
Socket socket = null;
DataOutputStream dataOutputStream = null;
try {
socket = new Socket(IPadresa, 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
slanje = "hy string";
dataOutputStream.writeUTF(slanje);
FileOutputStream outToFile = new FileOutputStream("slika.jpg");
int bytecount = 2048;
byte[] buf = new byte[bytecount];
InputStream IN = socket.getInputStream();
BufferedInputStream BuffIN = new BufferedInputStream(IN, bytecount)
int i = 0;
int filelength = 0;
while((i = BuffIN.read(buf, 0, bytecount)) != -1) {
filelength += i;
outToFile.write(buf, 0, i);
outToFile.flush();
}
IN.close();
BuffIN.close();
dataOutputStream.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MORE INFORMATIONS:
In server side I can see String that is send from Client. And I have that System.out.print("over"); command printed every time I send String to Server. Also I have System.out.print("check" + buf[0]); printed out from Server many times. So that is why I think that there is something wrong with Client side.
And my Client side doesn't throw any Exceptions... but I noticed that Client side never passed the while loop. It get stuck there.
I don't know what you mean by "my client side is not good", and I can't see any obvious errors that would stop it working entirely. If you could tell us what happens, that would help.
Meanwhile there are a couple of things wrong with the code you have presented:
You are violating industry accepted coding standards with names such as "BuffIn", "IN", "IPaddresa" and so on. All variable names in Java must start with a lowercase letter.
If you do this in private code that is your business. But if you are going to show your Java code to other people, you should conform to the standards. (And posting your code on SO is showing it to other people ...)
Since you are always trying to read a whole buffer's worth of data, replace in.read(buf, 0, bytecount) with in.read(buf).
There is no value in using a BufferedInputStream or BufferedOutputStream if you are only going to do large read or write calls on it. Even more so if you tell the stream to use the same size buffer as your the byte[] you are reading / writing.
Both your client and server side code could leak file descriptors. On the server-side it could leak in. On the client side, any or all of the streams' file descriptors could leak.