java.net.SocketException: connection reset on reading bytes - java

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)
{
}

Related

Java - Socketexception: Connection Reset

I'm currently working on a small chat-program. The 2 classes I have a problem with are the classes containing the clientside and the serverside of a socket. I want the client to read the lines the server sends. I get this error:
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 MainPanel.run(MainPanel.java:121)
at java.lang.Thread.run(Unknown Source)
I read, that this happens, because the socket connection gets closed on the serverside, but I can't see, where that happens in the code. Can someone explain, why this happens or how to fix it?
Codesnippet from client:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true) {
chatArea.append(br.readLine() + "\n"); //line 121
}
} catch(Exception ex) { ex.printStackTrace(); }
Codesnippet from server:
while(true) {
System.out.println("Waiting for someone to connect.");
Socket currentSocket = serverSocket.accept();
System.out.println("Someone connected.");
sockets.add(currentSocket);
new Thread(new Runnable() {
public void run() {
try {
while(true) {
BufferedReader br = new BufferedReader(new InputStreamReader(currentSocket.getInputStream()));
String input = br.readLine();
for(Socket socket : sockets) {
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println(input);
}
}
} catch(Exception ex) {
sockets.remove(currentSocket);
System.out.println("One connection lost.");
}
}
}).start();
}
When server application gets terminated, the TCP session which is bound to Socket object on the client side throws SocketException which is purely normal. There is nothing wrong with your scenario. What you have to do is that you have to handle SocketException both on the clientside and the server server side. Either client or server may terminate the TCP session. On the client side you may have a logic that may try to reinitialize the TCP session, whereas on the server side, you clear objects related to the TCP session.
a sample runner class :
public class TCPProcessor implements Runnable {
private Socket s;
private Thread th;
public TCPProcessor(Socket s) {
this.s = s;
th = new Thread(this);
tcpProcessors.add(this);
th.start();
}
public void stop() {
try {
s.close();
} catch (Exception e) {
LOGGER.trace("socket couldn't be closed");
}
th.interrupt();
}
#Override
public void run() {
Request r = null;
try {
ObjectInputStream inFromClient = new ObjectInputStream(s.getInputStream());
ObjectOutputStream outToClient = new ObjectOutputStream(s.getOutputStream());
while (isStarted()) {
final Object receivedObject = inFromClient.readObject();
// LOGGER.debug("Receiving "
// + ((Request) receivedObject).getRequestType() + " "
// + receivedObject);
r = (Request) receivedObject;
processId.set(r.getProcessId());
Response rs = new Response();
rs.setRequest(r);
rs.setServerFrom(GoldenNodeServer.this);
if (getOperationBase() != null) {
try {
Object s = ReflectionUtils.callMethod(getOperationBase(), r.getMethod(), r.getParams());
rs.setReturnValue(s);
} catch (Exception e) {
rs.setReturnValue(e);
}
outToClient.writeObject(rs);
} else {
rs.setReturnValue(new NoClientProxySetException());
}
}
} catch (EOFException e) {
// LOGGER.trace("eof occured");
} catch (SocketException e) {
if (e.toString().contains("Socket closed") || e.toString().contains("Connection reset")
|| e.toString().contains("Broken pipe")) {
} else {
stop();
LOGGER.error("Error occured" + (r == null ? "" : " while processing " + r) + " ", e.toString());
}
} catch (IOException | ClassNotFoundException e) {
stop();
LOGGER.error("Error occured" + (r == null ? "" : " while processing " + r) + " ", e.toString());
} finally {
tcpProcessors.remove(this);
}
}
}

exception connection reset when exiting the program

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.

EOFException after calling socket.shutdownOutput()

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.

Socket programming, multithreaded game, getting an End Of File Exception

I'm trying to implement a little game, where multiple clients have to connect to a server, and play together. Every one has a different GUI and they communicate through the class ClientConnect, which is a Runnable started from the GUI class. The problem is that i'm getting an EOFException at the first lines of code, when i'm trying to intanciate the inputstream. The server is of course started at the beginning and sending an object.
Here is a cut of the implementation where i get the exception.
What should i do?
public ClientConnect(InetAddress address, int port) throws IOException {
clientSock = new Socket(address, port);
}
#Override
public void run() {
ArrayList<Object> receivedObject = null;
try (ObjectInputStream fromServer = new ObjectInputStream(clientSock.getInputStream());
ObjectOutputStream toServer = new ObjectOutputStream(clientSock.getOutputStream()))
{
while(!move) {
receivedObject = (ArrayList<Object>) fromServer.readObject();
move = !(receivedObject.get(0).equals("you have to wait!!"));
}
actualPlayer = (String) receivedObject.get(0);
scoreCard = (List<String>) receivedObject.get(1);
highScore = (HashMap<String, Integer>) receivedObject.get(2);
numberOfPlayers = (int) receivedObject.get(3);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is the exception:
CShellExt::CShelljava.io.EOFException
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 edu.hm.se2.kniffel.ClientConnect.run(ClientConnect.java:41)
at java.lang.Thread.run(Unknown Source)
Ext()
The line 41 is the line with the try
I'm starting the ClientConnect thread in the GUI like that:
public void actionPerformed(ActionEvent arg0) {
//Online-Spiel starten
if(game.listLength()>0){
try {
client = new ClientConnect(InetAddress.getByName(null), 2000);
new Thread(client).start();
while (!client.getMove()) {
lblActualUser.setText("WAITING.... " + client.getActualPlayer() + " ist an der Reihe");
}
Got it!
I Got something blocking the serversocket to be opened!
On this evidence, the peer isn't creating an ObjectOutputStream at all, it's just connecting and then closing the socket.
You should construct the ObjectOutputStream before the ObjectInputStream, at both ends.

Connection reset, java

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().

Categories