套接字无法接收数据

发布于 2024-12-25 08:58:39 字数 2188 浏览 6 评论 0原文

我有一个实现serversocket 类的类,还有另一个实现客户端1.Socket 类的类。

所以我正在尝试做的就是这个。获取流后,我希望客户端向服务器发送一个数字,服务器将依次响应客户端,无论它是否是素数。它显示在 awt.Label 中。

但我无法收到任何回复。

以下是客户端构造函数的代码:

public ClientIsPrime()
{
    setLayout(new GridLayout(2,2));
    add(new Label("Enter a number: "));
    add(numEntry=new TextField(10));
    add(checkPrime=new Button("Check if number is Prime"));
    add(result=new Label("Result is shown here"));

    try
    {
        Socket client = new Socket(InetAddress.getLocalHost(), 5959);
        in=client.getInputStream();
        out=client.getOutputStream();
    }catch(UnknownHostException e)
    {
        result.setText("Local Host cannot be resolved");
    }catch(IOException e)
    {
        result.setText("IOException occured");
    }

    checkPrime.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            try
            {
                int num;
                num=Integer.parseInt(numEntry.getText());
                out.write(num);
                out.flush();

                int c;
                result.setText("");
                String s="";
                while((c=in.read())!=-1)
                    s+=((char)c);
                result.setText(s);
            }catch(IOException e)
            {
                result.setText("IOException occured");
            }catch(NumberFormatException e)
            {
                result.setText("Please enter a valid number.");
            }
        }
    });
}

服务器代码:

public static void main(String args[])throws IOException
{
    server=new ServerSocket(5959);

    socket=server.accept();

    System.out.println("connected");

    InputStream in=socket.getInputStream();
    OutputStream out=socket.getOutputStream();
    int c;  String numStr="";
    while((c=in.read())!=-1)
        numStr+=((char)c);
    int num=Integer.parseInt(numStr);
    if(num==3)
        out.write("Number is Prime".getBytes());
    else
        out.write("Number is not Prime".getBytes());
    out.flush();

    in.close();
    out.close();
}

它不是一个真正的应用程序。我在学习。

I have a class implementing serversocket class and there is another class implementing the client 1. Socket class.

So what I am trying to do is that. After getting the streams I want client to send a number to server and server will in turn respond to client whether it's prime or not. Which is display in an awt.Label.

But I am not able to receive any response.

Here is the code for client's constructor:

public ClientIsPrime()
{
    setLayout(new GridLayout(2,2));
    add(new Label("Enter a number: "));
    add(numEntry=new TextField(10));
    add(checkPrime=new Button("Check if number is Prime"));
    add(result=new Label("Result is shown here"));

    try
    {
        Socket client = new Socket(InetAddress.getLocalHost(), 5959);
        in=client.getInputStream();
        out=client.getOutputStream();
    }catch(UnknownHostException e)
    {
        result.setText("Local Host cannot be resolved");
    }catch(IOException e)
    {
        result.setText("IOException occured");
    }

    checkPrime.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            try
            {
                int num;
                num=Integer.parseInt(numEntry.getText());
                out.write(num);
                out.flush();

                int c;
                result.setText("");
                String s="";
                while((c=in.read())!=-1)
                    s+=((char)c);
                result.setText(s);
            }catch(IOException e)
            {
                result.setText("IOException occured");
            }catch(NumberFormatException e)
            {
                result.setText("Please enter a valid number.");
            }
        }
    });
}

Code for Server:

public static void main(String args[])throws IOException
{
    server=new ServerSocket(5959);

    socket=server.accept();

    System.out.println("connected");

    InputStream in=socket.getInputStream();
    OutputStream out=socket.getOutputStream();
    int c;  String numStr="";
    while((c=in.read())!=-1)
        numStr+=((char)c);
    int num=Integer.parseInt(numStr);
    if(num==3)
        out.write("Number is Prime".getBytes());
    else
        out.write("Number is not Prime".getBytes());
    out.flush();

    in.close();
    out.close();
}

It isn't a real app. I am learning.

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

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

发布评论

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

评论(2

时光是把杀猪刀 2025-01-01 08:58:39

有几个问题。

首先,您的服务器实现永远不会退出 while 循环。 InputStream.read() 的 API 声明它将阻塞,直到收到数据或关闭流。该流永远不会关闭,因此读取初始数据后将永远阻塞。

要解决这个问题,您必须决定您的协议是什么。见下文。

另一个问题是您从客户端以解析的文本形式写入。所以说 13(作为一个整数)。但你随后会像阅读一系列字符一样阅读它。线路上的 13 将被读取为某个控制字符。您需要保持写入数据和读取数据的方式一致。

我的建议是制定一个基本协议。在写入端使用DataOutputStream,在读取端使用DataInputStream,然后匹配两侧的读/写调用以确保一致。

A few problems.

First your server implementation will never exit the while loop. The API for InputStream.read() states that it will block until data is received or the stream is closed. The stream is never closed so the reading will block forever after reading the initial data.

To solve this problem you must decide what your protocol is. See below.

The other problem is that you are writing from the client as a parsed int of text. So say 13 (as an int). But you are then reading it as if it were a sequence of characters. 13 on the wire will be read as some control character. You need to be consistent with how you write data and read data.

My suggestion would be to have a basic protocol. Use DataOutputStream on the writing side and DataInputStream on the reading side and then match the read/write calls on both sides to ensure you are consistent.

两相知 2025-01-01 08:58:39

如果您想通过线路发送整数,那么在原始套接字流之上放置一个 DataOutputStream/DataInputStream 会无限容易,只需执行 writeInt() 和 readInt()

If you want to sent integers across the wire it is infinitely easier to layer a DataOutputStream/DataInputStream on top of the raw socket streams and just do writeInt() and readInt()

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