In Java API,
Socket socket = serverSocket.accept();
BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter toSocket = new PrintWriter(socket.getOutputStream());
//do sth with fromSocket ... and close it
fromSocket.close();
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();
In the above code, after I close the InputStream fromSocket, it seems that the socket connection is not available anymore--the client wont receive the "is socket connection still available" message.
Does that mean that closing the inputstream of a socket also closes the socket itself?
Yes, closing the input stream closes the socket. You need to use the shutdownInput method on socket, to close just the input stream:
//do sth with fromSocket ... and close it
socket.shutdownInput();
Then, you can still send to the output socket
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();
Related
I have a small TCP server and client where the server is performing inside a while(true) loop meanwhile my client isn't. However when i send a message from the client to the server, the server isn't able to read it. Below is the code and error:
SERVER:
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("[SERVER]: Server launched on port " + port);
while (true) { // the while loop makes the server continuously accept client request
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println(reader.readLine());
}
CLIENT:
Socket socket = new Socket("localhost", 9101);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("lol");
ERROR:
Exception in thread "main" java.net.SocketException: Connection reset
The error occurs when we try to read data in the server. With all that being said, if i surround the out.println() method in the client in a while(true) loop the error goes away and the code works fine. So i'm wondering why the i get this exception when the server is inside an infinite loop but the client isn't.
hi I have an application that sends text to a device and the device shows it on a display. for transferring data I'm using socket in a AsyncTask class
try {
Socket socket = new Socket(DISPLAY_IP, DISPLAY_PORT);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(params[0]);
output.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
the problem is I can't read response from socket after sending data. when I'm getting input stream from socket and reading line I'm not getting anything and the device is not showing the sent data from me till I close the application so I think the socket is blocking when I'm doing that
try {
Socket socket = new Socket(DISPLAY_IP, DISPLAY_PORT);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(params[0]);
output.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = bufferedReader.readLine();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
how can I send data and read response from socket?
You are trying to communicate with two (client) Sockets. For communication you must implement on one side a (client) java.net.Socket and on the other a java.net.ServerSocket.
You may read further here.
What are you trying to achieve?
When using InputStream it will get data that came from other side, not the data that you just sent.
And as SirGregg said readLine will hang until the whole line is received.
Client
Socket socket = new Socket("ip", 5555);
PrintStream out = new PrintStream(socket.getOutputStream());
out.println("Hello Server!");
out.close();
socket.close();
Server
ServerSocket serverSocket = new ServerSocket(5555);
while (true) {
//keep listening
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = in.readLine();
System.out.println(line);
in.close();
socket.close();
}
if ignore concurrency issue, is the way to close sockets connection correct?
if ignore concurrency issue, is the way to close sockets connection correct?
Yes, but you don't need to close the socket if you've already closed the output stream.
if client closed socket immediately after sent data, will it cause some exception like 'socket is close' while server tries to read data from stream?
No. 'Socket is closed' means you closed the socket and then continued to use it. As long has the client has read everything the server is going to send, the client can close the socket: the server will read all the data the client has sent, and then get end-of-stream on the next read.
I created a java chat application (client and server)
Everything works fine when I'm on my LAN (using LAN IP address of the server into my client).
But when I'm using the Internet address of my server in my client, the strings are sent only when I close the output Data stream of my client (and all the strings are sent at once).
Here's a quick snap of my code (I have port forward from 6791 to 6790 in the example below),
My server (thread):
// this line is actually on my global server class, used below with theServer
ServerSocket svrSocket= new ServerSocket(6790);
//wait for incoming connection
connectionSocket = svrSocket.accept();
connectionSocket.setSoTimeout(10000);
// free the accepting port
svrSocket.close();
//create a new thread to accept future connections (creates a new svrSocket)
theServer.openNewConnection();
//create input stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
boolean threadRunning = true);
while (threadRunning) {
//System.out.println("thread: in the while");
try {
Thread.sleep(100);
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
catch...
}
My client:
InetAddress dnsName;
Socket clientSocket;
PrintWriter out;
dnsName = InetAddress.getByName("myAddress.me");
clientSocket = new Socket(dnsName.getHostAddress(), 6791);
Thread.sleep(10);
out = new PrintWriter(clientSocket.getOutputStream(), true );
int i=140;
while (i>130){
try {
out.println(Integer.toString(i));
out.flush();
Thread.sleep(200);
}
catch(Exception e) {
e.printStackTrace();
}
i--;
}
out.flush();
out.close();
clientSocket.close();
I've tried with DataOutStreams, there's nothing to do.
My server will only receive the strings when out.close() is called on client side.
Is there a reason why, over the Internet, the data stream has to be closed for data to be sent? Is there a way around this? Am I doing something wrong?
I have this code on Server side :
Server Side:
ServerSocket listenTransferSocket = new ServerSocket(6000);
Socket connectionTransferSocket = listenTransferSocket.accept();
DataOutputStream outTransferToClient =
new DataOutputStream(connectionTransferSocket.getOutputStream());
{
....................... (Some code)
.......................
}
outTransferToClient.write(fileInBytes,0,numOfBytes);
System.out.println("File send");
**// outTransferToClient.close();**
BufferedReader inFromClientR =
new BufferedReader(new InputStreamReader(connectionTransferSocket.getInputStream()));
Client Side:
Socket fileTransferSocket = new Socket("localhost",6000);
DataInputStream in = new DataInputStream(new BufferedInputStream(
fileTransferSocket.getInputStream()));
OutputStream out = new FileOutputStream(new File("./TransferedFiles/"+fileName));
byte[] by = new byte[numOfBytes];
while ((read = in.read(by, 0, numOfBytes)) != -1) {
out.write(by,0,read);
}
DataOutputStream outToServerR =
new DataOutputStream(fileTransferSocket.getOutputStream());
System.out.println("checkC");
outToServerR.writeBytes("Transfer completed \n");
and i get the following exception when i try to open the BufferedReader if i close this:
outTransferToClient.close();
Exception in thread "main" java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:788)
at Server.main(Server.java:92)
if i dont the while loop on Client Side never stops.. any help????
DataOutputStream extends FilterOutputStream which has the close() method
From docs
Closes this output stream and releases any system resources associated with the stream.
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.
Aside, its always a nice practice to have methods like close() in finally block
Yes, closing a DataOutputStream closes the underlying OutputStream as well. The Javadoc for DataOutputStream#close() states:
The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.
Plus, the Javadoc for Socket states that when you close a Sockets inputStream or outputStream, it will also close the associated socket.
So you cannot reuse the socket after having closed the DataOutputStream that wrapped either of its streams.