“java.net.SocketException:连接重置”在我的 Runnable 类中,为什么?

发布于 2024-12-02 08:09:25 字数 4907 浏览 0 评论 0原文

我在套接字编程应用程序中有“服务器”的代码,并且在这行代码的以下代码的第 26 行中有此异常 java.net.SocketException

while((line=bReader.readLine())!=null){

导致此异常的问题是什么?

服务器:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
    final public int PORT=1212;
    private Socket client;
    private ServerSocket server;
    private BufferedReader bReader;
    private PrintWriter pWriter;
    public void run(){
        try {
            System.out.println("Start server ...");
            server=new ServerSocket(PORT);
            while(true){
                System.out.println("Start listening on PORT "+PORT+" ...");
                client=server.accept();
                System.out.println("Connection with client["+client.getInetAddress().getHostName()+"]");
                bReader=new BufferedReader(new InputStreamReader(client.getInputStream()));
                pWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
                    String line="";
                    while((line=bReader.readLine())!=null){
                        RecoginzeMessage(line);
                    }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                client.close();
            //  server.close();
                bReader.close();
                pWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
    public void RecoginzeMessage(String msg){
        String msg_params[]=msg.split(":");
        switch(Integer.parseInt(msg_params[0])){
        case 0:// Authetication process 
            System.out.println("Authentication new client");
            AuthenticateUser(msg_params[1],msg_params[2]);
            break;
        }
    }
    public void AuthenticateUser(String username, String password){
        if(username.equals("adham")&&password.equals("adham")){
            pWriter.println("1");
            pWriter.flush();
        }
        else{
            pWriter.println("0");
            pWriter.flush();
        }
    }
}

此代码用于“客户端”..

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client implements Runnable {
    public final String SERVER_IP="127.0.0.1";
    public final int PORT=1212;
    private Socket client;
    private BufferedReader bReader;
    private PrintWriter pWriter;
    Scanner sc=new Scanner(System.in);
    public Client(){
        if(client==null)
            try {
                client=new Socket(SERVER_IP,PORT);
                bReader=new BufferedReader(new InputStreamReader(client.getInputStream()));
                pWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


    }
    public void run(){

            System.out.print("Enter username: ");
            String username=sc.nextLine();

            System.out.print("Enter password: ");
            String password=sc.nextLine();

            if(login(username,password)){
                System.out.print(">logged in successfuly");             
            }else{
                System.out.print(">Inavlied username or password");                             
            }

    }
    private boolean login(String username, String password){
        try{
            pWriter.println("0:"+username+":"+password);
            pWriter.flush();
            while(true){
                String line="";
                while((line=bReader.readLine())!=null){
                    if(line.equals("1"))
                        return true;
                    else
                        return false;
                }

            }
        }catch(Exception ex){
            return false;
        }
    }
}

编辑:运行客户端线程的类

public class RunClient {    
    public static void main(String args[]){
        Client cThread=new Client();
        cThread.run();
    }
}

编辑:运行服务器线程的类

public class RunServer {
    public static void main(String args[]){
        Server sThread=new Server();
        sThread.run();
    }
}

I have this code for "Server" in socket programming application, and I have this Exception java.net.SocketException in line 26 of the following code in this line of code:

while((line=bReader.readLine())!=null){

What is the problem causing this exception?

Server:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
    final public int PORT=1212;
    private Socket client;
    private ServerSocket server;
    private BufferedReader bReader;
    private PrintWriter pWriter;
    public void run(){
        try {
            System.out.println("Start server ...");
            server=new ServerSocket(PORT);
            while(true){
                System.out.println("Start listening on PORT "+PORT+" ...");
                client=server.accept();
                System.out.println("Connection with client["+client.getInetAddress().getHostName()+"]");
                bReader=new BufferedReader(new InputStreamReader(client.getInputStream()));
                pWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
                    String line="";
                    while((line=bReader.readLine())!=null){
                        RecoginzeMessage(line);
                    }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                client.close();
            //  server.close();
                bReader.close();
                pWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
    public void RecoginzeMessage(String msg){
        String msg_params[]=msg.split(":");
        switch(Integer.parseInt(msg_params[0])){
        case 0:// Authetication process 
            System.out.println("Authentication new client");
            AuthenticateUser(msg_params[1],msg_params[2]);
            break;
        }
    }
    public void AuthenticateUser(String username, String password){
        if(username.equals("adham")&&password.equals("adham")){
            pWriter.println("1");
            pWriter.flush();
        }
        else{
            pWriter.println("0");
            pWriter.flush();
        }
    }
}

and this code for "client" ..

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client implements Runnable {
    public final String SERVER_IP="127.0.0.1";
    public final int PORT=1212;
    private Socket client;
    private BufferedReader bReader;
    private PrintWriter pWriter;
    Scanner sc=new Scanner(System.in);
    public Client(){
        if(client==null)
            try {
                client=new Socket(SERVER_IP,PORT);
                bReader=new BufferedReader(new InputStreamReader(client.getInputStream()));
                pWriter=new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


    }
    public void run(){

            System.out.print("Enter username: ");
            String username=sc.nextLine();

            System.out.print("Enter password: ");
            String password=sc.nextLine();

            if(login(username,password)){
                System.out.print(">logged in successfuly");             
            }else{
                System.out.print(">Inavlied username or password");                             
            }

    }
    private boolean login(String username, String password){
        try{
            pWriter.println("0:"+username+":"+password);
            pWriter.flush();
            while(true){
                String line="";
                while((line=bReader.readLine())!=null){
                    if(line.equals("1"))
                        return true;
                    else
                        return false;
                }

            }
        }catch(Exception ex){
            return false;
        }
    }
}

Edit: The class to run Client thread

public class RunClient {    
    public static void main(String args[]){
        Client cThread=new Client();
        cThread.run();
    }
}

Edit: The class to run Server thread

public class RunServer {
    public static void main(String args[]){
        Server sThread=new Server();
        sThread.run();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海不蓝 2024-12-09 08:09:25

客户端看起来是一个线程执行的,但是仅仅实现Runnable是不正确的,你需要创建一个Thread并将Runnable传递给它。客户端不会无限期地执行,因此客户端隐式地完成关闭(JVM)套接字,并且服务器收到此异常以指示(客户端关闭套接字)。

The client seems to be executed by a thread, but just implementing Runnable is not correct, you need to create a Thread and pass the Runnableto it. The client not executes indefinitely, so the client finishes and closes implicitly (the JVM) the socket and the Server get this exception to indicate that (client closes the socket).

一紙繁鸢 2024-12-09 08:09:25

为了避免 SocketException 尝试添加 wait() 或类似的内容,作为客户端应用程序中 run() 方法中的最后一条语句。

To avoid SocketException try out to add wait() or similar something as the last statement in run() method in the client app.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文