Java SocketException:软件导致连接中止

时间:2015-05-18 17:05:39

标签: java

我正在尝试开发客户端 - 服务器交换程序,当我尝试从客户端向服务器发送数据时,我遇到了SocketException。我看过其他答案,但没有一个符合我的确切情况;我有两次调用osw.write,其中只有一个有效。

客户:

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;
    }


}

服务器:

    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();
    }

}

很抱歉,如果代码缩进看起来有点奇怪,我不习惯使用堆栈溢出。

3 个答案:

答案 0 :(得分:0)

您正在关闭服务器类中的套接字:

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

答案 1 :(得分:0)

我认为这是问题所在。这是您发送到服务器的第一条消息。

客户端

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

由于您的服务器在获得13 char后停止阅读,因此在读取第一条消息后会关闭连接。

服务器

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

答案 2 :(得分:0)

使用TestNG运行功能测试时遇到了同样的异常。对我来说这是一个版本问题。卸载它并安装旧版本修复了我的问题。请阅读以下帖子以获取相关信息。

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