I get the following error:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at test.SocketTest.main(SocketTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
I don't know why I get it. Any idea?
I'm using this code:
for Client:
public class SocketTest {
public static void main(String[] args) {
try {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 5000);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Request request = new Request();
request.setInputId("user_1233423333");
request.setOperation(3);
outputStream.writeObject(request);
outputStream.flush();
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
and for the Server:
public class ServerSocketTest {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Request request = (Request) inputStream.readObject();
System.out.println(request.getInputId());
System.out.println(request.getOperation());
writer.write("ok");
writer.flush();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I think that this codes should work, but I don't know Why I get this error. Any idea, guys?
EDIT:
OS = windows 8.1 64-bit
I've tested on my Ubuntu and everything was ok.
Your test program is exiting without closing the socket. This causes the connection to be reset (TCP RST) instead of issuing an orderly close (TCP FIN). On some platforms.
Another problem is that you are reading lines in the client, but you aren't sending a line. You need to send a line terminator.
Client side
Try any one
readLine() method looks for a complete line or a string that is ended by new line character \n.
Use Scanner that contains hasNextLine() and nextLine() methods.
Server Side
Try any one
Append new line character \n in the message for e.g. ok\n.
Use PrintWriter instead of BufferedWriter and use println() method that automatically appends a new line character in the message. Use auto-flush property of the PrintWriter to avoid calling flush() method manually.
Complete sample code:
ServerSocketTest.java
public class ServerSocketTest {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),
true);
System.out.println(inputStream.readObject());
writer.println("ok");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
SocketTest.java
public class SocketTest {
public static void main(String[] args) {
try {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 5000);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(new InputStreamReader(socket.getInputStream()));
outputStream.writeObject("Hello");
String s;
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I have a client which continuously both sends and receives data messages which works fine, however when I close/stop the client then I get the following single line error:
java.net.SocketException: Socket closed
Despite me closing the socket in a try-finally enclosing. Now my question is as to why I receive this error and whether or not this behavior is normal or not and how to properly handle this error. Below is my code:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = null;
try {
socket = new Socket("localhost", 9101);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while(true) {
try {
System.out.println(in.readLine());
} catch (IOException e) {
e.printStackTrace();
System.out.println("error");
}
}
}
});
thread.start();
System.out.println("Write to server:");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String message = scanner.nextLine();
out.println(message);
out.flush();
};
} finally {
socket.close();
}
}
I think you're trying to read from the socket in a separate thread even after your main thread closes the socket the other thread is still trying to read from it.
I guess a simple check-in your other thread might resolve this issue:
if(socket.isClosed())
System.out.println(in.readLine());
I'm skeptical about the use of isClosed but I think it is worth trying out.
I am having problem even with this very basic client-server application. The client is not sending data/ the server is not receiving. I cannot understand where is the problem. I am even starting to think that i did not understand anything about sockets.
This is the Server code:
public class Server
{
public static void main(String args[])
{
try{
ServerSocket serverSocket = new ServerSocket(3000);
Socket socket = serverSocket.accept();
System.out.println("Client connected: "+socket.getInetAddress.toString());
Scanner scanner = new Scanner(socket.getInputStream());
while(true)
{
System.out.println(scanner.nextLine());
}
}catch(IOException e)
{
System.out.println("error");
}
}
}
This is the client code:
public class Client
{
public static void main(String args[])
{
Socket socket;
PrintWriter printWriter;
try {
socket = new Socket("127.0.0.1", 3000);
printWriter = new PrintWriter(socket.getOutputStream(), true);
while(true)
{
printWriter.write("frejwnnnnnnnnnnnnnnnnnnnnnnnnosfmxdawehtcielwhctowhg,vort,hyvorjtv,h");
printWriter.flush();
}
}catch(IOException e)
{
System.out.print("error\n");
}
}
}
If I run both on the same machine, the server prints correctly "client connected .....", but then prints no more.
What is the problem?
The server reads the next line. The client doesn't send any line ending. So the server can't possibly know that the line is supposed to be ended, and blocks until it finds an EOL in the stream. Or until the client closes its socket.
In client code, you decorate your output stream with PrintWriter, so you can use println.
Replace
printWriter.write("frejwnnnnn...rjtv,h");
printWriter.flush();
by:
printWriter.println("frejwnnnnn...rjtv,h");
Flush is useless since have request autoflush (true in PrintWriter constructor).
In server code, you can use a BuffererdReader decorator instead of Scanner:
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
So i'm trying to make a server/client solution using BufferedReader and BufferedWriter, but it won't work! Using only DataInputStream and DataOutputStream worked perfectly fine, but nothing printed out with the Buffered objects. Where is my error?
public class TServer {
static final int PORT = 8001;
static final int QUEUE = 50;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT, QUEUE)) {
Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println(input.readLine());
output.write("this is the server!");
output.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
public class TClient {
static final String HOST = "localhost";
static final int PORT = 8001;
public static void main(String[] args) {
try (Socket socket = new Socket(HOST, PORT)) {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
output.write("this is the client");
output.flush();
System.out.println(input.readLine());
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Using only DataInputStream and DataOutputStream worked perfectly fine, but nothing printed out with the Buffered objects.
The Client is sending the following:
output.write("this is the client");
The Server is trying to read a line with the BufferedReader:
System.out.println(input.readLine());
But no line will be received as the end of line terminator is not sent (hence, the method will block (same goes for the Server, which does not send the end of line terminator)). See the API for BufferedReader, which states:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
You are using readLine method of BufferedReader, so you should write newline-terminated string in corresponding BufferedWriter. Like:
output.write("this is the client");
output.newLine();
I am new to socket programming in java so facing a problem seems not difficult but unable to solve due to unfamiliarity. Following are codes for Client and Server.
Server Code:
public class connectionServer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String clientSentence;
String capitalizedSentence;
BufferedReader inFromClient;
DataOutputStream outToClient;
BufferedReader inFromUser;
try {
ServerSocket welcomeSocket = new ServerSocket(70);
Socket connectionSocket;
connectionSocket = welcomeSocket.accept();
System.out.println("Connection accepted for " + connectionSocket.getInetAddress() + ": " + connectionSocket.getPort());
InputStreamReader input = new InputStreamReader(connectionSocket.getInputStream());
inFromClient = new BufferedReader(input);
while (true)
{
if(input.ready())
{
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
String tempString = "FROM SERVER: What's problem......";
try
{
Thread.currentThread().sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
outToClient = new DataOutputStream(connectionSocket.getOutputStream());
if(outToClient != null)
{
outToClient.writeBytes(tempString + "\n");
outToClient.flush();
}
}
}
catch (IOException e)
{
System.out.println(e);
e.printStackTrace();
}
}
}
Client Code:
public class connectionClient {
static Socket clientSocket = null;
//////////////////////////////////////////
//////////////////////////////////////////
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String sentence;
String modifiedSentence;
attachShutDownHook();
try
{
clientSocket = new Socket("127.0.0.1", 70);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());;
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes("FROM CLIENT 2: Hello \n\n");
while(clientSocket.isConnected())
{
sentence = "Please reply me....";
try
{
Thread.currentThread().sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
if(inFromServer.ready())
{
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
}
outToServer.writeBytes("FROM CLIENT 2:" + sentence + "\n");
outToServer.flush();
}
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
System.exit (0) ;
}
}
}
When I stop the client following exception is thrown on server side
java.net.SocketException: Connection reset by peer: socket write error
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:132)
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:276)
at connectionserver.connectionServer.main(connectionServer.java:57)
Any help in this regard will be highly appreciated. Thanks
This usually means you have written to an connection that had already been closed by the peer. In other words, an application protocol error.
Your code needs work.
Don't use ready(): just block in read() until data arrives. At present you're smoking the CPU while ready() returns false. This is probably causing the error.
isConnected() is always true after you connect the socket. It won't magically return false when the peer closes his end. You have to detected that via EOS or an exception. Looping on while (isConnnected()) isn't valid.
Don't mix streams and readers and writers. You're using a BufferedInputStream: use a BufferedWriter at the other end.
I am trying to write a small program, that opens a server, creates a client that connects to this server and receives a message from it.
This is the Code so far
public static void main(String[] args) {
final ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(12345);
Thread t = new Thread(){
public void run(){
try {
Socket server = serverSocket.accept();
PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
writer.write("Hello World");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
Socket client = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = reader.readLine();
System.out.println("Received " + message);
} catch (IOException e1) {
e1.printStackTrace();
}
}
If i run program it keeps waiting in readLine() - so obviously the client does not receive the message from the server.
Has anyone got an idea why this isn' working?
Your reading thread is waiting for a newline in the data stream. Just change the server to use:
writer.write("Hello World\r\n");
and you'll get the result you were expecting. Alternatively, you can just close the server socket, and then readLine will return when it reaches the end of the data stream.
You should put the readline in a loop as follows:
public static void main(String[] args) {
final ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(12345);
Thread t = new Thread() {
public void run() {
try {
Socket server = serverSocket.accept();
PrintWriter writer = new PrintWriter(server.getOutputStream(), true);
writer.write("Hello World");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
Socket client = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
// Check this --------------------------------------------------->
String message = null;
while ((message = in.readLine()) != null) {
System.out.println("Received " + message);
break; //This break will exit the loop when the first message is sent by the server
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
You can read this documentation for further explanation: http://download.oracle.com/javase/tutorial/networking/sockets/