0

I'm trying to develop a client-server exchange program, and when I try to send data from client to server, I'm running into a SocketException. I've looked at other answers but none of them fit my exact case; I have two calls to osw.write, and only one of them works.

Client:

package me.primesearch.client;

import java.math.BigInteger;
import java.net.*;
import java.io.*;

public class PrimeSearchClient {

    public static void main(String[] args) throws IOException{
        Socket connection = null;
        try{
            /** Define a host server */
            String host = "localhost";
            /** Define a port */
            int port = 25564;
            StringBuffer instr = new StringBuffer();
            System.out.println("SocketClient initialized");
            /** Obtain an address object of the server */
            InetAddress address = InetAddress.getByName(host);
            /** Establish a socket connetion */
            connection = new Socket(address, port);
            /** Instantiate a BufferedOutputStream object */
            BufferedOutputStream bos = new BufferedOutputStream(connection.
                    getOutputStream());
            /** Instantiate a BufferedInputStream object for reading
            /** Instantiate a BufferedInputStream object for reading
             * incoming socket streams.
             */

            BufferedInputStream bis = new BufferedInputStream(connection.
                getInputStream());
            /**Instantiate an InputStreamReader with the optional
             * character encoding.
             */

            InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

            /**Read the socket's InputStream and append to a StringBuffer */
            int c;

                /** Instantiate an OutputStreamWriter object with the optional character
                 * encoding.
                 */
            OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
            while(true){
                    String process = "drq " + (char) 13;
                    /** Write across the socket connection and flush the buffer */
                    osw.write(process);
                    osw.flush();

                    while ( (c = isr.read()) != 13)
                        instr.append( (char) c);

                    for(int i=0;i<50;i++){
                        BigInteger offset=new BigInteger(instr.toString()).add(BigInteger.valueOf(i));
                        if(isProbablyPrime(offset)){
                            process = "pri" + " " + offset + " " + (offset.divide(new BigInteger("50"))).toString() + (char) 13;
                            System.out.println(process);
                            /** Write across the socket connection and flush the buffer */

                            osw.write(process);        //This doesn't work
                            osw.flush();
                            System.out.println("Prime found at " + offset);
                        }
                    }

            }

        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    public static boolean isProbablyPrime(BigInteger n) {
        if(n.longValue()!=0){
            BigInteger lessOne = n.subtract(BigInteger.ONE);
            // get the next prime from one less than number and check with the number
            return lessOne.nextProbablePrime().compareTo(n) == 0;
        }
        return false;
    }


}

Server:

    package me.primesearch.server;

import java.net.*;
import java.io.*;

public class PrimeSearchServer implements Runnable {
    private Socket connection;
    @SuppressWarnings("unused")
    private int ID;

    PrimeSearchServer(Socket s, int i) {
        this.connection = s;
        this.ID = i;
    }

    @SuppressWarnings("resource")
    public static void main(String[] args) {
         int port = 25564;
         int count = 0;
            try{
                ServerSocket socket1 = new ServerSocket(port);
                System.out.println("MultipleSocketServer Initialized");
                while (true) {
                  Socket connection = socket1.accept();
                  Runnable runnable = new PrimeSearchServer(connection, ++count);
                  Thread thread = new Thread(runnable);
                  thread.start();
                }
              }
              catch (Exception e) {
                  e.printStackTrace();
              }



    }

    @Override
    public void run() {
        try {
              BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
              InputStreamReader isr = new InputStreamReader(is);
              int character;
              StringBuffer process = new StringBuffer();
              while((character = isr.read()) != 13) {
                process.append((char)character);
              }
              System.out.println(process);
              String returnCode="0";
              if(process.toString().split(" ")[0].equals("drq")){
                  System.out.println("Job request recieved");
                  File file = new File("packages.txt");
                  //Process input
                  try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                        String line;
                        String prevLine="";
                        boolean i = false;
                        int count=0;
                        while ((line = br.readLine()) != null) {
                            System.out.println("Looking for a package to send");
                           // process the line.
                            if(line.equals("0")){
                                System.out.println("Sending package " + count);
                                returnCode = Integer.toString(count);
                                i = true;
                                break;
                            }
                            prevLine = line;
                            count++;
                            System.out.println("No packages found");
                        }

                        if(!i){
                            returnCode = prevLine;
                            try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("packages.txt", true)))) {
                                System.out.println("Creating new package");
                                out.println("0");
                                returnCode=Integer.toString(count);
                            }catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
              } else if (process.toString().split(" ")[0].equals("pri")){
                  System.out.println("Prime request recieved");
                  try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("primes.txt", true)))) {
                      out.println(Integer.parseInt(process.toString().split(" ")[1]));
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                  updateLine(Integer.parseInt(process.toString().split(" ")[2]));
              }

              BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
              OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
              osw.write(returnCode + (char)13);
              osw.flush();

              process = new StringBuffer();
            }
            catch (Exception e) {
              System.out.println(e);
            }
            finally {
              try {
                connection.close();
             }
              catch (IOException e){
                  e.printStackTrace();
              }
            }
        }

    private void updateLine(int lines) throws IOException {
        String data="packages.txt";
        BufferedReader file = new BufferedReader(new FileReader(data));
        String input = "";
        String line;

        for(int i=0;i<lines;i++){
            input+=file.readLine()+System.lineSeparator();
        }
        file.readLine();
        while ((line = file.readLine()) != null)
            input += line + System.lineSeparator();


        FileOutputStream os = new FileOutputStream(data);
        os.write(input.getBytes());

        file.close();
        os.close();
    }

}

Sorry if the indenting on the code looks a bit strange, I'm not used to using stack overflow.

2
  • What's the details of the exception? Commented May 18, 2015 at 17:06
  • @Buddy Here's the stack trace: java.net.SocketException: Software caused connection abort: 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:153) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:297) at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141) ... Commented May 18, 2015 at 17:17

3 Answers 3

1

You are closing the socket in your server class:

        finally {
          try {
            connection.close();
         }
          catch (IOException e){
              e.printStackTrace();
          }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was the problem!
0

I think this is the problem. This is the first message you're sending to the server.

Client

 String process = "drq " + (char) 13;
 osw.write(process);
 osw.flush();

And since your server stops reading after it gets a 13 char it closes the connection after it reads the first message.

Server

while((character = isr.read()) != 13) {
     process.append((char)character);
}

Comments

0

I was getting the same exception when running functional test using TestNG. For me it was a version issue. Uninstalling it and installing older version fixed my issue. Read the following post for information.

https://github.com/cbeust/testng-eclipse/issues/91

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.