我是服务器/客户端应用程序的新手,并且“线程“主”中的异常” java.net.SocketException:连接重置”不断弹出

时间:2019-03-27 20:56:44

标签: java tcp server client

这是必须将服务器连接到库mysql数据库的服务器代码。我试图从终端运行作者类作为参数的CLIENT类,但是由于某种原因,我一直在获取重置连接。我知道这意味着客户端没有收到数据,而是关闭了连接,但是我不确定为什么会发生

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;

import java.sql.*; 

public class LibraryServer {

  private int port = 8080;

  private ServerSocket serverSocket;

  //URL of DB server and authentication string
  static final String dbURL =
    "jdbc:mysql://localhost/" + 
    "user=root&password="...";

  //In the constructor, load the Java driver for the MySQL DB     server
  //to enable this program to communicate with the database 
  public LibraryServer() throws ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");
  }

  public void acceptConnections() {

    try {
  //similar to the WelcomeSocket in the PowerPoint slides
      serverSocket = new ServerSocket(port);
    }
    catch (IOException e) {
      System.err.println("ServerSocket instantiation failure");
      e.printStackTrace();
      System.exit(0);
     }

//Entering the infinite loop
    while (true) {
      try {
  //wait for a TCP handshake initialization (arrival of a "SYN"     packet)
        Socket newConnection = serverSocket.accept();
        System.out.println("accepted connection");

  //Now, pass the connection socket created above to a thread and     run it in it

  //First create the thread and pass the connection socket to it
  //This is a non-blocking function: constructor of the class     ServerThread
        ServerThread st = new ServerThread(newConnection);

  //Then, start the thread, and go back to waiting for another TCP  connection
  //This also is not blocking
        new Thread(st).start();
      }
      catch (IOException ioe) {
        System.err.println("server accept failed");
      }
    }
  }

  public static void main(String args[]) {

LibraryServer server = null;
   try {
      //Instantiate an object of this class. This will load the JDBC database driver
      server = new LibraryServer();
    }
    catch (ClassNotFoundException e) {
      System.out.println("unable to load JDBC driver");
      e.printStackTrace();
      System.exit(1);
    }

//call this function, which will start it all...
    server.acceptConnections();
  }

  //Internal class
  class ServerThread implements Runnable {

    private Socket socket;
    private DataInputStream datain;
    private DataOutputStream dataout;

    public ServerThread(Socket socket) {
  //Inside the constructor: store the passed object in the data member 
      this.socket = socket;
    }

//This is where you place the code you want to run in a thread
//Every instance of a ServerThread will handle one client (TCP connection)
    public void run() {
      try {
  //Input and output streams, obtained from the member socket object 
        datain = new DataInputStream(new BufferedInputStream
          (socket.getInputStream()));
        dataout = new DataOutputStream(new BufferedOutputStream
          (socket.getOutputStream()));
      }
      catch (IOException e) {
        return;
      }
      byte[] ba = new byte[6];
      boolean conversationActive = true;

      while(conversationActive) {
        String author = null;
        try {
    //read from the input stream buffer (read a message from client)
          datain.read(ba,0,6);
          author = new String(ba);
          //Exit when a "Q" is received from a client
          if ((author.length() == 1) && 
              (author.toUpperCase().charAt(0) == 'Q')) {
            conversationActive = false;
          }
          else {
            System.out.println("requested author = " + author);
            String names = getNames(author);
            System.out.println("names: " + names);
            System.out.println("writing " + names.length() + " bytes");

   //Write to the output stream buffer (send a message to client)
            dataout.write(names.getBytes(),0,names.length());
            dataout.write("\n".getBytes(),0,1);
            dataout.flush();
          }
        }
        catch (IOException ioe) {
          conversationActive = false;
        }
      }
      try {
        System.out.println("closing socket");
        datain.close();
        dataout.close();
  //When the server receives a "Q", we arrive here
        socket.close();
      }
      catch (IOException e) {
      }
    }

//This function is for communicating with the database server
//using API provided by the JDBC driver loaded at the top
    private String getNames(String author) {
      String result = "None available";
      Connection conn = null;
      try {
        conn = DriverManager.getConnection(dbURL);
        System.out.println("YALLA");
        Statement stmt = conn.createStatement();
        String query = "SELECT Title " +
                       "FROM Book " + "WHERE Author = " + 
                       "'" + author.trim() + "'" +
                       " ORDER BY Book_ID";
        System.out.println("query = " + query);
        ResultSet rs = stmt.executeQuery(query);
        StringBuffer sb = new StringBuffer();
        while (rs.next()) {
          sb.append(rs.getString(1));
          sb.append(", ");
          sb.append(rs.getString(2));
          sb.append('$');
        }
        result = sb.toString();
      }
      catch (SQLException e) {
        System.out.println(e.getMessage());
        result = "server error";
      }
      finally {
        if (conn != null) {
          try {
            conn.close();
          }
          catch (SQLException e) {
          }
        }
      }
      return result;
    }
  }
}

客户代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class LibraryClient {
    private static String AuthName = null;
    @SuppressWarnings("resource")
    public static void main(String[] args) throws IOException  {
        // TODO Auto-generated method stub
        try {
            AuthName = args[0];
            }
        catch (ArrayIndexOutOfBoundsException error) {
            System.out.println("Please Enter a Filename!");
        }
         Socket socket = new Socket("192.168.0.114",8080);
          OutputStream out = socket.getOutputStream();
         PrintWriter p = new PrintWriter(out,true);
         p.println("test");


     BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     String response = in.readLine();
      System.out.println(response);


    }

}

0 个答案:

没有答案