拒绝与客户端的连接

u0sqgete  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(421)

我搜索了一下,找不到解决我问题的相关方法。我正试图发送整数到服务器,用多线程计算它的阶乘。但我得到“连接被拒绝”的错误。这是我的密码:

package ohw3;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.TitledBorder;

public class MathClient extends JFrame {

    static JTextArea jta = new JTextArea(5, 1);

public static void main(String[] args) {
    new MathClient();
}

public MathClient() {
    setTitle("Factorial Calculator");
    setSize(400, 300);
    setLocationRelativeTo(null);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    add(new JScrollPane(jta), BorderLayout.NORTH);

    JPanel panel1 = new JPanel();
    panel1.setBorder(new TitledBorder("Factorial Calculator"));
    panel1.setFocusable(true);

    JLabel necess = new JLabel("Please Enter the Integer:");
    panel1.add(necess, BorderLayout.SOUTH);

    final JTextField integer = new JTextField(15);
    panel1.add(integer);

    JButton send = new JButton("Calculate");
    panel1.add(send, BorderLayout.NORTH);

    add(panel1);

    setVisible(true);

    try {
        // Create a server socket
        ServerSocket serverSocket = new ServerSocket(1080);
        serverSocket.setSoTimeout(3000);
        jta.append("MultiThreadServer started at '' " + new Date() + " ''\n");

        // Number a client
        int clientNo = 1;

        while (true) {
            // Listen for a new connection request
            final Socket socket = new Socket("localhost", 1080);

            // Display the client number
            jta.append("Starting thread for client " + clientNo
                    + " at '' " + new Date() + " ''\n");

            // Find the client's host name, and IP address
            InetAddress inetAddress = socket.getInetAddress();
            jta.append("Client " + clientNo + "'s host name is "
                    + inetAddress.getHostName() + "\n");
            jta.append("Client " + clientNo + "'s IP Address is "
                    + inetAddress.getHostAddress() + "\n");

                send.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int value = Integer.parseInt(integer.getText());

                        // Create a new thread for the connection
                        MultiThreadedMathServer task = new      MultiThreadedMathServer(socket, value);

                        // Start the new thread
                        new Thread(task).start();
                }
              });

            // Increment clientNo
            serverSocket.close();
            clientNo++;
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

class MultiThreadedMathServer implements Runnable {

    private final Socket socket; // A connected socket
    private final int numb; // A connected socket

    /**
     * Construct a thread
     */
    public MultiThreadedMathServer(Socket socket, int numb) {
        this.socket = socket;
        this.numb = numb;
    }

    /**
     * Run a thread
     */
    @Override
    public void run() {
        try {
            // Create data input and output streams
            DataInputStream inputFromClient = new DataInputStream(
                    socket.getInputStream());
            DataOutputStream outputToClient = new DataOutputStream(
                    socket.getOutputStream());

            // Continuously serve the client
            while (true) {
                // Receive radius from the client
                int integer = inputFromClient.readInt();

                // Compute area
                int fact = 1;

                for (int i = integer; i > 0; i--) {
                    fact = fact * i;
                }

                // Send area back to the client
                outputToClient.writeDouble(fact);

            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

}
lskq00tm

lskq00tm1#

正如fvu所说,您的服务器不接受套接字。也, MultiThreadedMathServer 线程初始化似乎放错了位置。您应该在服务器上接收到的每个新接受的套接字连接上创建它。比如:

while(true){
    MultiThreadedMathServer task = new MultiThreadedMathServer(serverSocket.accept(), value);
    new Thread(task).start(); //this thread will deal with this client
}

因为, serverSocket.accept() 将一直挂起,直到新连接到达,到达后一个新线程将处理该套接字,服务器将返回 accept() 又是新插座。

gojuced7

gojuced72#

您的服务器没有接受连接的规定,因此它不知道如何处理传入的连接。

Socket clientSocket = socket.accept();
// and then you can use the socket for reading and writing.

但是我建议您复习一个关于java网络的好教程,比如官方教程。

相关问题