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?
Related
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();
}
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 3 years ago.
I'm using Java Socket to send a file to server and then get a response back. The problem is every time i try to read the response from server, it makes the file-reading part of the server hang. I really need your help on what's going on here?
Here is SERVER code:
ServerSocket server = new ServerSocket(PORT);
Socket client = server.accept();
BufferedInputStream netInStream = new BufferedInputStream(client.getInputStream());
BufferedOutputStream netOutStream = new BufferedOutputStream(client.getOutputStream());
String outFileName = "output/test";
File outputFile = new File(outFileName);
if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs();
}
FileOutputStream fileOutStream = new FileOutputStream(outputFile);
BufferedOutputStream bufOutStream = new BufferedOutputStream(fileOutStream);
// read file from client and save
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = netInStream.read(buffer)) > 0) {
bufOutStream.write(buffer, 0, bytesRead);
bufOutStream.flush();
Log.line("Bytes read: " + bytesRead);
}
// clean up file IO
// ...
// send response to client
netOutStream.write("File received by server".getBytes());
netOutStream.flush();
// clean up network IO
// ...
CLIENT code:
Socket client = new Socket(DOMAIN_SERVER, PORT_SERVER);
BufferedOutputStream netOutStream = new BufferedOutputStream(client.getOutputStream());
BufferedInputStream netInStream = new BufferedInputStream(client.getInputStream());
String inFileName = "input/test";
File file = new File(inFileName);
if (!file.exists()) {
client.close();
return;
}
FileInputStream fileInSream = new FileInputStream(file);
BufferedInputStream bufInStream = new BufferedInputStream(fileInSream);
// read and send file to server
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = bufInStream.read(buffer)) > 0) {
netOutStream.write(buffer, 0, bytesRead);
netOutStream.flush();
Log.line("Bytes sent: " + bytesRead);
}
// clean up file IO
// ...
// read response from server
StringBuilder res = new StringBuilder();
byte[] charBuf = new byte[128];
int msgBytesRead = 0;
while ((msgBytesRead = netInStream.read(charBuf)) > 0) {
res.append(new String(charBuf, 0, msgBytesRead));
}
Log.line(res.toString());
// clean up network IO
// ...
The flow is, client sends a file to server, server reads the file and saves to its local storage then the server sends a response string to client, the client reads the response and prints it out on the screen.
If the code is like above, the server will not exit the while-loop and hang, therefor the client second while-loop doesn't read anything and hang, too.
But if i comment/remove the client second while-loop, both programs run and no hang occurs. File transfer is also success.
Your expectation is that read returns with no data once the server is done sending the file. This expectation is wrong. read will only return with no data if the server has closed the TCP connection and the flush you show does not close the connections but only makes sure that all buffered data are written to the TCP connection.
This means the server can still send more data after the flush and that's why your client is hanging in the read and waiting for more data.
I am trying to send file from java app to a remote c# application through socket
here is the code
C#
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(ip, 1593);
NetworkStream networkStream = tcpClient.GetStream();
StreamReader sr = new StreamReader(networkStream);
//read file length
int length = int.Parse(sr.ReadLine());
byte[] buffer = new byte[length];
networkStream.Read(buffer, 0, (int)length);
//write to file
BinaryWriter bWrite = new BinaryWriter(File.Open(strFilePath, FileMode.Create));
bWrite.Write(buffer);
bWrite.Flush();
bWrite.Close();
tcpClient.Close();
Java app
ServerSocket serverSocket = new ServerSocket(1593);
System.out.println("Server started and waiting for request..");
Socket socket = serverSocket.accept();
System.out.println("Connection accepted from " + socket);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
File file = new File(strFileToSend);
// send file length
out.println(file.length());
// read file to buffer
byte[] buffer = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.read(buffer, 0, buffer.length);
// send file
BufferedOutputStream bos = new BufferedOutputStream(
socket.getOutputStream());
bos.write(buffer);
bos.flush();
serverSocket.close();
System.out.println("File has been send ... ");
The exception raised from the client side
Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host
The server application said it has sent successfully the file.
Thanks in advance.
Your problem is that you are issuing serverSocket.close(); too soon. The Server Socket is not supposed to be closed just because a single transaction between the client and the server concluded. The server socket is supposed to stay open for as long as the server is running.
So, when you close the server socket, the response to the client is still in transit, (it probably hasn't even begun transmitting yet from the server to the client,) so the client gets disconnected prematurely, before it has had the chance to receive or fully process the response.
I've a client-server connection. The client sends out request to server in a predefined format to initiate some processing at server. Server does this processing and then returns the result in predefined format to client.
Processing at server may take upto 15 mins.
I'm using reqObject.toString() to convert the request/response to string and then send through network using readUTF and writeUTF (reading the whole buffer).
Now the issue:
Data send by client is received properly and the processing happens. Once that is done, if the processing takes LESSTHAN 5 mins, once server sends the data, client receives it normally.
But if processing takes MORETHAN 5-6 mins, server sends back data, but client doesnt receive it (times out after given timeout period).
Code snippet:
Client:
Socket server = null;
OutputStream outToServer = null;
DataOutputStream out = null;
InputStream inFromServer = null;
DataInputStream in = null;
if(msg != null){
try
{
server = new Socket(serverIp, serverPort);
server.setSoTimeout(1000 * 60 * timeoutInMins); //set to 30 mins
outToServer = server.getOutputStream();
out = new DataOutputStream(outToServer);
out.writeUTF(msg);
out.flush();
// now wait for Server reply
inFromServer = server.getInputStream();
in = new DataInputStream(inFromServer);
responseString = in.readUTF();
// do something with response
}
Server:
ServerSocket serverSocket = null;
Socket client = null;
try{
serverSocket = new ServerSocket(port);
} catch (Exception e) {//log this}
try
{
while(true)
{
client = serverSocket.accept();
if(client.getRemoteSocketAddress() != null){
try{
ReqObject request = getRequest(client);
// do processing. this may take upto 10-15 mins at max
sendBackResponse(client, request);
}
// do remaining
private void sendBackResponse(Socket client, ReqObject result) throws IOException {
DataOutputStream out = null;
try{
out = new DataOutputStream(client.getOutputStream());
String outToClient = result.toString();
out.writeUTF(outToClient);
out.flush();
} finally {
try{out.close();}catch(IOException e){}
}
}
private ReqObject getRequest(Socket client) throws IOException {
DataInputStream in = null;
in = new DataInputStream(client.getInputStream());
String incoming = in.readUTF();
return convertMessageToRequest(incoming);
}
The connection was getting disconnected/blocked by a firewall which was in between, after 5 mins of inactivity.
To overcome this, I started sending heartbeat message (with junk data) every 2 minute. This kept the connection alive till the operation completed.
Note: The keepalive() method provided by java didn't help..
I'm developing a server to client file transfer program on java, and couldn't figure out how to fix the following code as I don't know much about socket programming. The code is Client side's codes:
String receiverIP = null;
int serverPort = 0;
hostIP = args[0];
serverPort = Integer.parseInt(args[1]);
String fileToSend = args[2];
byte[] aByte = new byte[1];
int bytesR;
Socket clientSocket = null;
Socket connectSocket = null;
BufferedOutputStream ToClient = null;
InputStream is = null;
try {
ToClient = new BufferedOutputStream(connectSocket.getOutputStream());
clientSocket = new Socket(hostIP, serverPort);
is = clientSocket.getInputStream();
} catch (IOException ex) {
System.out.println(ex);
}
as for my problem, I get a null pointer exception on line 14 (undoubtedly since currently connectSocket is null), but I have no idea what can I assign on connectSocket(if it was on server side a connection accept socket could've been assigned to begin writing after the connecion is established.)
Contrary to what you seem to believe, you do not need two separate sockets to read and write to the server. One socket will suffice. You can call the getInputStream method to get a stream to read from the server, and getOutputStream to get a stream to write to the server. You don't need two sockets, just one.