当前位置: 首页 > 知识库问答 >
问题:

套接字异常:套接字关闭- Java

田鸿彩
2023-03-14

我最近一直在玩套接字,但是我遇到了一个问题…当我从服务器接收数据时,我得到一个“java.net.套接字异常:套接字关闭”异常。我没有在任何地方关闭套接字,事实上,我唯一使用关闭()的地方是扫描仪上从System.in读取文本;

以下是我的代码:

客户:

package packets.sidedcomputer;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import packets.MessagePacket;
import packets.sender.PacketSender;
import packets.side.Side;

public class Client extends SidedComputer
{
    volatile boolean finished = false;

    volatile String username;

    volatile Server server;

    public Socket clientSocket;

    public ClientReciever reciever;

    public Client(Server server, String username) throws UnknownHostException, IOException
    {
        this.username = username;
        this.server = server;
        this.reciever = new ClientReciever(this);
    }

    public void stopClient()
    {
        finished = true;
    }

    @Override
    public void run()
    {
        Scanner scanner = new Scanner(System.in);

        reciever.start();

        while(!finished)
        {
            try 
            {
                this.clientSocket = new Socket("192.168.1.25", 10501);

                String line;

                while((line = scanner.nextLine()) != null)
                {     
                    PacketSender sender = new PacketSender();

                    System.out.println("Client sending message \"" + line + "\" to server");
                    sender.sendPacket(new MessagePacket(line, username), clientSocket);
                }
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }

        }

        scanner.close();
    }

    @Override
    public Side getSide() 
    {
        return Side.CLIENT;
    }
}

服务器:

package packets.sidedcomputer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import packets.Packet;
import packets.data.PacketData;
import packets.info.ClientInfo;
import packets.reciever.PacketReciever;
import packets.sender.PacketSender;
import packets.side.Side;

public class Server extends SidedComputer
{
    volatile boolean finished = false;

    public ServerSocket serverSocket;

    public volatile List<ClientInfo> clients = new ArrayList<ClientInfo>();

    public void stopServer()
    {
        finished = true;
    }

    public Server()
    {
        try 
        {
            serverSocket = new ServerSocket(10501);
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        try 
        {
            while (!finished)
            {
                Socket clientSocket = serverSocket.accept();  

                if(clientSocket != null)
                {
                    ClientInfo clientInfo = new ClientInfo(clientSocket);

                    this.clients.add(clientInfo);

                    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                    String dataString;

                    while((dataString = in.readLine()) != null)
                    {
                        PacketReciever packetReciever = new PacketReciever();

                        PacketData packetData = new PacketData();

                        packetData.decodeInto(dataString);

                        Packet packet = packetReciever.recievePacket(packetData, packetData.packetID, getSide(), clientSocket.getLocalAddress().getHostAddress().toString(), clientSocket.getLocalPort() + "");

                        PacketSender packetSender = new PacketSender();

                        for (ClientInfo client : this.clients)
                        {
                            PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
                            packetSender.sendPacketToClient(packet, out);
                        }
                    }
                }
            }
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public Side getSide() 
    {
        return Side.SERVER;
    }
}

数据包发送者:

package packets.sender;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import packets.Packet;
import packets.data.PacketData;

public class PacketSender implements IPacketSender
{
    @Override
    public void sendPacket(Packet packet, Socket socket)
    {
        if(packet.getDefualtID() == 0)
        {
            PacketData packetData = new PacketData(packet.getDefualtID());

            packet.writeData(packetData);

            String data = packetData.encodeIntoString();

            sendData(socket, data);
        }
    }

    protected void sendData(Socket socket, String data)
    {
        try 
        {

            try 
            (
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            ) 
            {
                out.println(data);
            } 
            catch (IOException e) 
            {
                System.err.println("Couldn't get I/O for the connection to " + socket);
                System.exit(1);
            } 
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }

    public void sendPacketToClient(Packet packet, PrintWriter out)
    {
        PacketData packetData = new PacketData(packet.getDefualtID());

        packet.writeData(packetData);

        String data = packetData.encodeIntoString();

        out.println(data);
    }
}

客户端接收器:

package packets.sidedcomputer;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import packets.data.PacketData;
import packets.reciever.PacketReciever;
import packets.side.Side;

public class ClientReciever extends Thread
{
    public Client client;

    public ClientReciever(Client client)
    {
        this.client = client;
    }

    volatile boolean running = true;

    public void stopRunning()
    {
        running = false;
    }

    @Override
    public void run()
    {
        while(running)
        {
            if(client.clientSocket != null)
            {
                try 
                {
                    BufferedReader in = new BufferedReader(new InputStreamReader(client.clientSocket.getInputStream()));
                    String line;

                    while((line = in.readLine()) != null)
                    {
                        PacketReciever reciever = new PacketReciever();

                        PacketData packetData = new PacketData();
                        packetData.decodeInto(line);

                        reciever.recievePacket(packetData, packetData.packetID, Side.CLIENT, client.clientSocket.getLocalAddress().getHostAddress().toString(), client.clientSocket.getPort() + "");
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

        }
    }
}

数据包接收器:

package packets.reciever;

import packets.Packet;
import packets.MessagePacket;
import packets.data.PacketData;
import packets.side.Side;

public class PacketReciever implements IPacketReciever
{
    @Override
    public Packet recievePacket(PacketData packetData, int id, Side side, String hostName, String port) 
    {
        Packet packet = null;

        if(id == 0)
        {
            packet = new MessagePacket();

            packet.readData(packetData);

            packet.execute(side, hostName + ":" + port);
        }

        return packet;
    }
}

共有1个答案

公孙驰
2023-03-14

我认为问题是您在发送方中尝试资源调用,它将在 try 块结束时调用 close(),从而关闭套接字。尝试在所有调用 sendData() 时使用单个 PrintWriter

 类似资料:
  • 我想创建能够与多个客户端连接的服务器,但我总是收到“套接字关闭”异常或从输入流中读取空值,以前我认为这是由于以错误的方式关闭套接字连接引起的,所以我发布了这个主题,但现在似乎这不是问题所在。 服务器方法 HandlerThread类 客户端模拟器 例外和问题 在客户端模拟器之前启动服务器,客户端模拟器没有任何异常,但是在服务器端,并没有收到所有数据,从控制台打印信息时,我看到“null”、“Hel

  • 我在tomcat日志中每两分钟就会出现一次异常: 警告nio。ReadHandler[hz.\u hzInstance\u 1\u xyz.IO.thread-in-2]-[127.0.0.1]:5702[xyz][3.2.3]hz_hzInstance_1_xyz。木卫一。线程2关闭套接字到endpoint地址[127.0.0.1]:5701,原因:java。木卫一。EOFEException:

  • 我正在为客户机发送对象到服务器,在服务器端修改该对象,并将其重新发送到客户机。将对象从客户机发送到服务器很好,它工作正常,但当我将对象发送回来时,它给出了异常,Socket关闭。这里是代码。IntString和ParentObj是我要发送对象的类。 服务器类 用于发送和接收对象的Send_recv类。

  • 我尝试用Java套接字API制作基本的Java聊天应用程序。但是当客户端终止时,它会引发以下异常, socketException:套接字关闭 我认为即使套接字已经关闭,BufferedReader流仍然尝试读取行消息。 但我不知道当客户端终止时,何时以及如何关闭BufferedReader流和套接字连接。 我完全被这部分卡住了。有什么想法吗?

  • 因此,我有一个客户机wich连续发送和接收数据消息,wich工作正常,然而,当我关闭/停止客户机时,我会得到以下单行错误: 尽管我试图关闭插座--最终封闭了。现在我的问题是为什么我会收到这个错误,这个行为是否正常,以及如何正确处理这个错误。下面是我的代码:

  • 我有一个硬件设备,我用TCP/IP与它通信。 您能对Windows或Java或任何其他导致此问题的相关设置进行映像吗?