I have a multithreaded server with a connection to MySQL and every time a I run it I get the same exception:java.net.SocketException: Connection reset
this is my server:
public void run(){
// synchronized(this){
try {
serverSocket = new ServerSocket(serverPort);
System.out.println("Server started on port " + serverPort);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
while(true){
Socket s = serverSocket.accept();
es.execute((Runnable) new WorkerThread(s));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
this is my worker thread:
String[] str = new String[10];
String arr;
try {
int i=0;
int b=0;
String message=null;
while(!Thread.currentThread().isInterrupted()) {
message=in.readLine();
if (message.equals("exit")){
System.exit(0);
}
// .... here I have other if statements
}
} catch (IOException | SQLException e1) {
e1.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and the exception :
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Pack.WorkerThread.run(WorkerThread.java:62)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
it appears here:
message=in.readLine();
If you exit the program using System.exit(0); your connection will be terminated which leads to this exception.
If you do not want this exception to be thrown, make sure to close inputstream using in.close() prior to calling System.exit(0) or terminating the thread.
Related
I had written a small code where I am trying to listen on particular port as follows (just trying out something) :
public class Test {
public static class MyThread extends Thread {
ServerSocket ss = null;
public MyThread(int port){
try {
ss = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Exception in assigning port : " + port);
e.printStackTrace();
}
}
public void stopListening(){
try {
ss.close();
} catch (IOException e) {
System.out.println("Exception in closing socket : " + ss.getLocalPort());
e.printStackTrace();
}
}
public void run(){
try {
ss.accept();
} catch (IOException e) {
System.out.println("Exception in listening on port : " + ss.getLocalPort());
e.printStackTrace();
}
}
}
public static void main(String[] args) {
List<MyThread> threadList = new LinkedList<>();
for (int i = 50000; i < 50005; i++) {
MyThread thread = new MyThread(i);
threadList.add(thread);
thread.start();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
for (MyThread myThread : threadList) {
myThread.stopListening();
}
}
}
But I am unable to start even a single thread , for every ss.accept() I keep getting :
Exception in listening on port :
I get the following exception in each case :
java.net.SocketException: socket closed
at java.net.DualStackPlainSocketImpl.accept0(Native Method)
at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
at java.net.PlainSocketImpl.accept(Unknown Source)
at java.net.ServerSocket.implAccept(Unknown Source)
at java.net.ServerSocket.accept(Unknown Source)
at com.harman.hlacssmdw.Test$MyThread.run(Test.java:40)
I checked the ports from 50000 to 50000 using netstat -anp , none of theme are occupied.
I am unable to understand what am I doing wrong, Please help !!!
The ServerSocket is closed because you close it by calling stopListening(). That leads to an Exception for all Threads waiting on accept() of that ServerSocket.
This is may look like a repeated question but, it is not. I have tried looking for an answer for this over 48 hours with no result.
Firstly, is closing PreparedStatment & ResultSet necessary in SQLite JDBC Connection? because I am unable to do so.
try {
Class.forName(database.getJDBC_DRIVER());
cnn = DriverManager.getConnection(database.getDB_URL());
p = cnn.prepareStatement(query);
rs = p.executeQuery();
p.close();
cnn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
System.out.println(p.isClosed());
if (cnn != null) cnn.close();
System.out.println(p.isClosed());
} catch (SQLException e) {
e.printStackTrace();
}
}
As you can see, I closed PreparedStatement inside the try block. However, When I'm checking the state of same outside the try block, the result is always false. (which means it isn't closed).
Besides, if I have below code in the finally block, it throws an error stating the connection is closed. I am super confused on what to do. Should I just leave it as it is. Wouldn't my code have some leakage?
} finally {
try {
if (p != null) p.close(); *// It errors out here...*
if (cnn != null) cnn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
Below is the stack trace -
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at tg.cat.DropDown.getData(DropDown.java:28)
at tg.loginscreen.LoginScreenLayout.<init>(LoginScreenLayout.java:22)
at tg.cat.CatMain.getScene(CatMain.java:27)
at tg.cat.CatMain.start(CatMain.java:18)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(Unknown Source)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/855499929.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/186276003.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/1635925971.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/237061348.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/2117255219.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The finally block is executed regardless of whether an exception was thrown or not. So you don't need to use it to close the connection again, but to use it as the only place you close the connection. Second, note that closing a connection will not reset the variable to null:
try {
Class.forName(database.getJDBC_DRIVER());
cnn = DriverManager.getConnection(database.getDB_URL());
p = cnn.prepareStatement(query);
rs = p.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (p != null) {
p.close();
}
if (cnn != null) {
cnn.close();
}
} catch (SQLException e) {
System.err.println("Can't close an object, not much I can do");
}
}
Mureinik is right, but even better to use the try-with-resources feature, so that you don't even have to worry about closing anything (manually) in the first place.
try (Connection cnn = DriverManager.getConnection(database.getDB_URL());
PreparedStatement p = cnn.prepareStatement(query)) {
// prepare your statement
try (ResultSet rs = p.executeQuery()) {
// process result set
}
} catch (SQLException e) {
throw new RuntimeException("Unexpected SQLException", e);
}
like the headline says I´m getting an EOFException on the serverside after i called shutdownOutput() at the clientside
this is at the serverside:
public void getRestaurant() {
String tempRestaurant=null;
try { BufferedReader fr =
new BufferedReader( new FileReader( "Restaurant.txt" ));
tempRestaurant = fr.readLine();
System.out.println( tempRestaurant );
System.out.println("writing tempRestaurant is the next Step");
oos.writeObject(tempRestaurant);
System.out.println("tempRestaurant has been written");
oos.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
and this is the code at the clientside:
protected String doInBackground(Void... params) {
connecttoServer();
System.out.println("connecting to server...");
try {
oos.writeInt(1);
System.out.println("next step is closing");
serverside.shutdownOutput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("connected to server");
Restaurant=(String) ois.readObject();
System.out.println("doInBackground(): "+Restaurant);
and this is the error code:
java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at prealphaserverpackage.clientsidethreads.handlerequest(Serverpart.java:355)
at prealphaserverpackage.clientsidethreads.run(Serverpart.java:156)
pls comment if you need any further informations i will put them online as soon as possible :)
I forgot to call oos.flush(); While the server was still waiting for the data, I closed the stream. That was the reason for the EOFException.
i am trying to create a little server in java using sockets.
The sockets are connected but when i send data from my client to my server it gives an exception.
stacktrace (UPDATED):
IOException on socket listen: java.net.SocketException: Connection reset
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at org.codox.game.network.NetworkController$doComms.run(NetworkController.java:81)
at java.lang.Thread.run(Unknown Source)
if you need more information tell me
any suggestions are welcome
thx
-- EDITED --
full server code:
class doComms implements Runnable
{
private Socket server;
PackageHandler packageHandler;
doComms(Socket server)
{
this.server = server;
packageHandler = new PackageHandler();
}
public void run()
{
try
{
ObjectInputStream ois = new ObjectInputStream(server.getInputStream());
ClientPackage clientPack = (ClientPackage) ois.readObject();
RespondPackage rp = packageHandler.handlePackage(clientPack);
ObjectOutputStream ous = new ObjectOutputStream(server.getOutputStream());
ous.writeObject(rp);
ous.flush();
server.close();
System.out.println("Connection was finished and closed.");
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ioe)
{
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
full client code:
SocketHints hints = new SocketHints();
hints.keepAlive = true;
hints.connectTimeout = 2000;
Socket socket;
try
{
socket = Gdx.net.newClientSocket(Protocol.TCP, "127.0.0.1", 12346, hints);
ClientPackage client = new ClientPackage();
client.setRequestType(RequestType.ping);
ObjectOutputStream ous = new ObjectOutputStream(socket.getOutputStream());
ous.writeObject(client);
ous.flush();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
RespondPackage response = (RespondPackage) ois.readObject();
System.out.println("Respone type = " + response.getRequestType());
} catch (UnknownHostException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e)
{
}
I am getting a lot of connection reset errors, trough debugging i found out that the code is found within these lines:
//set up output stream for objects
output = new ObjectOutputStream(socket.getOutputStream());
output.flush(); //flush the output buffer to send header information
// Read a message sent by client application
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
The error occurs at this line:
String message = (String) ois.readObject();
The error message:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at org.bitbucket.c4d3r.ConnectionListener.listen(ConnectionListener.java:47)
at org.bitbucket.c4d3r.ConnectionListener.<init>(ConnectionListener.java:27)
at org.bitbucket.c4d3r.ConnectionHandler.connectionServer(ConnectionHandler.java:46)
at org.bitbucket.c4d3r.ConnectionHandler.run(ConnectionHandler.java:24)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I know that the connection reset is caused by a socket that's closed unexpectedly, however i am quite new to sockets and i am unable to find what i am doing wrong. Therefore i was hoping that someone could help me out with this. For a better vision of everything i have copied a bigger block of code beneath
private DomainController dc;
private Socket socket;
private boolean changed;
private ObjectOutputStream output;
private ObjectInputStream ois;
private Map json;
public ConnectionListener(DomainController dc, Socket socket) {
this.dc = dc;
this.socket = socket;
listen();
}
#Override
public void run() {
listen();
return;
}
#SuppressWarnings("finally")
public void listen() {
try
{
//set up output stream for objects
output = new ObjectOutputStream(socket.getOutputStream());
output.flush(); //flush the output buffer to send header information
// Read a message sent by client application
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
boolean inProgress;
//CHECK IF THERE ARE GIVEN COMMANDS
if(message.substring(0, 8).equalsIgnoreCase("COMMAND="))
{
switch(message.substring(8))
{
case "askMinigames":
//System.out.println("Sending minigames list");
output.writeObject(new String(dc.getProp().getProperty("minigames")));
output.flush(); //flush output to client
break;
}
}
} catch (SocketException ex) {
System.out.printf("Connection reset\n");
ex.printStackTrace();
} catch (IOException e) {
System.out.println("Input exception");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try
{
if(ois != null) {
ois.close();
}
if(output != null) {
output.close();
}
if(socket != null) {
socket.close();
}
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
You need to use the same object input and output streams for the life of the socket, at both ends. As you are just sending strings, I don't really see why you're using object streams at all: you could use e.g. DataOutputStream.writeUTF() and DataInputStream.readUTF().