Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Connection reset by peer

Posted on 1999-07-27
12
Medium Priority
?
511 Views
Last Modified: 2010-04-16
Hallo

I try to write a client in java who shall communicate with a server written in c++. Port is 55301. The server echo back everything with :----: append to the data.

It works well if I use telnet but in java I get exception "Connection Reset by peer and "Socket closed" when I try to recieve previous message.

The message "Socket closed" is recieved first when the previous message have been rec. I think that the socket works due to the thread is blocking when it waits for a connection.

The javacode is in an applet.
Server is Linux (GNU c++), Apache server.
Client is Windows 98, Netscape Browser.
The Client in java is compiled with JDK and written with emacs.

A few lines of the code:

try
    {
        st = new Socket(ia, portData);
        dis = new DataInputStream(st.getInputStream());
        dos = new DataOutputStream(st.getOutputStream());
    }
catch(IOException e)

-----

try
   {
        dos.writeChars(txt.getText());
   }
catch(IOException e)

----
This code run in a separate Thread

String str = dis.readLine();
if(str == null) break;
txta.append(str);
0
Comment
Question by:tord_f
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +1
12 Comments
 

Expert Comment

by:tny
ID: 1247217
I think you can lost the reference on the Socket variable. In this case garbage collector can destroy your socket
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247218
>> when I try to recieve previous message.

what 'previous message' ?

>> ... Apache server.

what is your server app ? web server ?

can you post the whole code ?
0
 

Author Comment

by:tord_f
ID: 1247219
I will have a solution, perhaps a few lines of code that solve my problem
0
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 

Author Comment

by:tord_f
ID: 1247220
Answer to heyhey

Prewious message is that message I send to the server who is sending it back to me.

Below the server program, compiled on SUSE Linux 6.1 and run on a 200 MHz
Pentium MMX

-------------Server main.cpp
#include "fastplan.h"
#include "comm.h"

int main()
{
      char * ch, chout[MAXSTR];
      
      comm *obj = new comm;
      if(obj->startlisten() == true)
      {
            while(true)
            {
                  ch = obj->recvData();
                  if(*ch == '\0') break;
                  if(*ch == 'q') break;
                  strcpy(chout, ch);
                  int slen = strlen(chout) - 2;
                  chout[slen] = '\0';
                  strcat(chout, ":---: Retur: ");
                  if(obj->sendData(chout) == false)
                  {
                        perror("sendData");
                        exit(1);
                  }
            }
      }
      else
      {
            perror("startlisten");
            delete obj;
            exit(1);
      }
      delete obj;
      return 0;      
}

-------------------------------- Server comm.cpp
#include "fastplan.h"
#include "comm.h"

// portC currently not used

comm::comm()
{
      comminit(0,0);
}

comm::comm(int portD, int portC)
{
      comminit(portD, portC);
}

comm::~comm()
{
            close(ns);
            close(s);
}

void comm::comminit(int portD, int portC)
{
      portD = (portD == 0 ? PORTDATA : portD);
      portC = (portC == 0 ? PORTCONTROL : portC);
      
  if ((s = socket(AF_INET, SOCK_STREAM, IP_TCP)) == -1)
      {
            perror("socket");
            exit(1);
      }
      len = sizeof(name);
      memset(&name, 0, len);
      name.sin_family = AF_INET;
      name.sin_port = htons(portD); // portC not used
      
      int inaddr = INADDR_ANY;
      memcpy(&name.sin_addr, &inaddr, sizeof(long));
      if(bind(s, (struct sockaddr *) &name, len) < 0)
      {
            perror("bind");
            exit(1);
      }
}

bool comm::startlisten()
{
      if(listen(s,5)<0) return false;
      if((ns = accept(s, (struct sockaddr *) &name, &len)) < 0) return false;
      return true;
}

char * comm::recvData()
{
      int count;
      
      count = recv(ns, bufrecvData,sizeof(bufrecvData), 0);
      if(count < 1) count = 0;

      bufrecvData[count] = '\0';
      return bufrecvData;
}

bool comm::sendData(char * data)
{
      if(send(ns, data, strlen(data), 0) < 0)
            return false;
      else
            return true;
}

Belov is a javaapplet, compiled with JDK and run on MS WIndows 98, Netscape 4.6
------------------- Javaprogram
import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.lang.*;

public class FastPlan extends Applet implements Runnable
{
    ThreadGroup thrg;
    Thread thr;

    int portData, portControl;
    boolean initOK = false;
    Button send, recv;
    TextField txt;
    TextArea txta;
    String ia;
    Socket st;
    DataInputStream dis;
    DataOutputStream dos;

    public void init()
    {
      try
          {
            portData = Integer.parseInt(getParameter("PortData"));
          }
      catch (Exception e)
          {
            portData = 55301;
          }
      try
          {
            portControl = Integer.parseInt(getParameter "PortControl"));
          }
      catch (Exception e)
          {
            portControl = 55302;
          }
      setLayout(new BorderLayout());
      send = new Button("Send");
      recv = new Button("Recieve");
      txt = new TextField(20);
      txta = new TextArea(8,20);
      Panel norr = new Panel();
      norr.setLayout(new FlowLayout());
      norr.add(send); norr.add(txt);
      add("North", norr);
      add("South", recv);
      add("Center",txta);
      ia = getCodeBase().getHost();
      try
          {
            st = new Socket(ia, portData);
            dis = new DataInputStream(st.getInputStream());
            dos = new DataOutputStream(st.getOutputStream());
          }
      catch(IOException e)
          {
            System.out.println("Error dis + dus " + e);
            return;
          }
      thrg = Thread.currentThread().getThreadGroup();
      initOK = true;
    }

    public void paint(Graphics g)
    {
      g.drawString("Adress " + ia,40,40);
    }
   
    public synchronized void start()
    {
      thr = new Thread(thrg, this);
      thr.start();
    }

    public synchronized void stop()
    {
      try
          {
            if (thr != null)
                {
                  thr.stop();
                }
          }
      catch (Exception e)
          {
          }
      thr = null;
    }

    public void restart()
    {
      stop();
      start();
    }

    public void run()
    {
      Thread me = Thread.currentThread();
      me.setPriority(3);
      System.out.println("SHOWRECV");
      showrecv();
    }

    public boolean action(Event e, Object o)
    {
      if(!initOK) return true;
      if(("Send").equals(o)) showsend();
      //      if(("Recieve").equals(o)) showrecv();
      repaint();
      return true;
    }

    void showsend()
    {
      try
          {
            dos.writeChars(txt.getText());
          }
      catch(IOException e)
          {
            System.out.println("Error showsend " + e);
            return;
          }
      
    }

    void showrecv()
    {
      try
          {
            while(true)
                {
                  String str = dis.readLine();
                  if(str == null) break;
                  txta.append("Ny linje");
                  txta.append(str);
                }
          }
      catch(IOException e)
          {
            System.out.println("Error showrecv " + e);
            return;
          }
    }
}



0
 

Expert Comment

by:tny
ID: 1247221
I heard about bug in Netscape some version. He closes connection when applet is stoped. Try don't stop thread.
0
 

Author Comment

by:tord_f
ID: 1247222
I dont think that the method stop is called. This method is usually called automatic when applet goes out och scope. i e changing URL to another site..
0
 

Author Comment

by:tord_f
ID: 1247223
Adjusted points to 400
0
 

Expert Comment

by:tny
ID: 1247224
Netscape calls stop/start when you make screen resizing
0
 

Author Comment

by:tord_f
ID: 1247225
I did not know that.

I have change class from DataInput/OutputStream to BufferedInput/OutputStrem and String to byte[] and it work fine from now. But I dont know why!

And I don't know what "Connection reset by peer" means and what I can do to avoid it in the future

Regards
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247226
DataInputStream uses a lot of (Unicode) encoding, so use it only when you communicate with other Java apps

> A data input stream lets an application read primitive
> Java data types from an underlying input stream in a
> machine-independent way. An application uses a data
> output stream to write data that can later be read
> by a data input stream.

> Data input streams and data output streams represent
> Unicode strings in a format that is a slight
> modification of UTF-8.

probably your DataInputStream expects some char encoded in 2 / 3 bytes - and when it receives only one byte (the last one) it throws "Connection reset by peer"
0
 
LVL 2

Accepted Solution

by:
zbang earned 800 total points
ID: 1247227
First, try to make the stream variable (and the socket object) synchronized.
reading and writing to a socket at the same time might be something that the OS does not like.

Second,
The old implementations of the Berkley Sockets supported port numbers below 32767 only. This still remains the de-facto standard on many implementations.

Try lowering the port number. Also, the high numbers are usually reserved for dynamically-assigned port numbers, so try using something like 8080, or 4040...

0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247228
so what was the problem ?
0

Featured Post

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.
Suggested Courses

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question